package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.executor.query.CommonDingtalkListQry;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.message.domain.entity.PushLinkEntity;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasUserEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.constant.EsNormalConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.AddressEnum;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.OtherExpenseSheetTypeEnum;
import com.xbongbong.paas.enums.OtherIncomeSheetTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.EsignHelp;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.FormDataValidateProductHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.help.ProGetHelp;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasCommentModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.model.PaasUserModel;
import com.xbongbong.paas.pojo.CustomerUserPojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.IsActiveAliyunCallVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.UserAndDepartmentGetVO;
import com.xbongbong.paas.service.CallCenterCommonService;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasMenuService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.helper.ReflectHelper;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.RoleSimpleVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.pro.appdetail.pojo.MobileDetailDialPhonePojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailDirectBlockPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailExecutorBlockPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailManagerBlockPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailScriptPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusBlockPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailTextBlockPojo;
import com.xbongbong.pro.appdetail.pojo.dto.PhoneForDialGetDTO;
import com.xbongbong.pro.appdetail.pojo.dto.ReadMessageSetDTO;
import com.xbongbong.pro.appdetail.pojo.dto.SingleDataMessageGetDTO;
import com.xbongbong.pro.appdetail.pojo.vo.PhoneForDialGetVO;
import com.xbongbong.pro.appdetail.pojo.vo.SingleDataMessageGetVO;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.dto.MobileDetailThroughDTO;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.detailtab.dto.MarketActivityEffectGetDTO;
import com.xbongbong.pro.detailtab.pojo.DataDetailTabPojo;
import com.xbongbong.pro.detailtab.pojo.TabWorkFlowPojo;
import com.xbongbong.pro.detailtab.vo.MarketActivityEffectTargetVO;
import com.xbongbong.pro.enums.AmountFlagEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ReceiveStatusEnum;
import com.xbongbong.pro.enums.RefundStatusEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessTypeErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ContractErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PurchaseErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.fund.enums.ModelTypeEnum;
import com.xbongbong.pro.enums.permission.enums.DeleteProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.PrintProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.UpdateProPermissionAliasEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.marketManage.pojo.dto.RelationSaleClueListDTO;
import com.xbongbong.pro.marketManage.pojo.vo.RelationSaleClueListVO;
import com.xbongbong.pro.message.enums.RefEntityEnum;
import com.xbongbong.pro.message.model.PushLinkModel;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.message.pojo.MessagePojo;
import com.xbongbong.pro.message.service.MessageListService;
import com.xbongbong.pro.service.toolbox.statistic.help.FormHelp;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO;
import com.xbongbong.pro.webdetail.pojo.WorkReportDetailStatisticResultPojo;
import com.xbongbong.pro.weblist.pojo.CustomerCommunicatePojo;
import com.xbongbong.pro.weblist.pojo.vo.CommunicateVO;
import com.xbongbong.pro.workreport.pojo.vo.WorkReportDetailStatisticsVO;
import com.xbongbong.process.operate.ProcessFieldHelp;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.BomUserEntity;
import com.xbongbong.saas.domain.entity.ClueUserEntity;
import com.xbongbong.saas.domain.entity.CommunicatePlanUserEntity;
import com.xbongbong.saas.domain.entity.ContactUserEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.ContractUserEntity;
import com.xbongbong.saas.domain.entity.CustomerFocusEntity;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.InventoryProductEntity;
import com.xbongbong.saas.domain.entity.InvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.MarketActivityUserEntity;
import com.xbongbong.saas.domain.entity.OpportunityFocusEntity;
import com.xbongbong.saas.domain.entity.OpportunityUserEntity;
import com.xbongbong.saas.domain.entity.PayBalanceEntity;
import com.xbongbong.saas.domain.entity.PayPlanSheetUserEntity;
import com.xbongbong.saas.domain.entity.PayPlanUserEntity;
import com.xbongbong.saas.domain.entity.PaymentBalanceEntity;
import com.xbongbong.saas.domain.entity.PaymentSheetUserEntity;
import com.xbongbong.saas.domain.entity.PaymentTaskUserEntity;
import com.xbongbong.saas.domain.entity.PaymentUserEntity;
import com.xbongbong.saas.domain.entity.ProductionOrderUserEntity;
import com.xbongbong.saas.domain.entity.PurchaseInvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.PurchaseUserEntity;
import com.xbongbong.saas.domain.entity.QuotationUserEntity;
import com.xbongbong.saas.domain.entity.RefundUserEntity;
import com.xbongbong.saas.domain.entity.SaleStageEntity;
import com.xbongbong.saas.domain.entity.SupplierContactUserEntity;
import com.xbongbong.saas.domain.entity.SupplierUserEntity;
import com.xbongbong.saas.domain.entity.WarehouseUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CreditLimitStatusEnum;
import com.xbongbong.saas.enums.CreditTemporaryApplyStatusEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticDistributorEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticEnum;
import com.xbongbong.saas.enums.CustomerStatementStatusEnum;
import com.xbongbong.saas.enums.FormTypeEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.ListOptionTabEnum;
import com.xbongbong.saas.enums.MobileDetailBottomOperationEnum;
import com.xbongbong.saas.enums.MobileDetailSummaryEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OrderOutStockExpressStatusEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorAccountEnum;
import com.xbongbong.saas.enums.business.DistributorContactEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.MarketActivityEffectTargetEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OrderOutStockEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.PaymentTaskEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.BomStatusEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.dictionary.CommunicatePlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.ContactLevelEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.DistributorAccountStatusEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentTaskStatusEnum;
import com.xbongbong.saas.enums.dictionary.ProductionOrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.ReturnStatusEnum;
import com.xbongbong.saas.enums.dictionary.ReturnedStatusEnum;
import com.xbongbong.saas.enums.dictionary.ShipStatusEnum;
import com.xbongbong.saas.enums.dictionary.TransferNewStatusEnum;
import com.xbongbong.saas.enums.dictionary.WorkOrderShipStatusEnum;
import com.xbongbong.saas.help.DetailTabDataPermissionHelp;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.InvoiceCommonHelper;
import com.xbongbong.saas.help.ProDetailHandlerHelp;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.help.SaasDetailPermissionHelp;
import com.xbongbong.saas.help.SaasGetHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.BomUserModel;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.ContactUserModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InventoryProductModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.InvoiceRelationshipModel;
import com.xbongbong.saas.model.LikeModel;
import com.xbongbong.saas.model.MarketActivityUserModel;
import com.xbongbong.saas.model.OpportunityFocusModel;
import com.xbongbong.saas.model.OpportunityUserModel;
import com.xbongbong.saas.model.PayBalanceModel;
import com.xbongbong.saas.model.PayPlanSheetUserModel;
import com.xbongbong.saas.model.PayPlanUserModel;
import com.xbongbong.saas.model.PaymentBalanceModel;
import com.xbongbong.saas.model.PaymentSheetUserModel;
import com.xbongbong.saas.model.PaymentTaskUserModel;
import com.xbongbong.saas.model.PaymentUserModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.ProductionOrderUserModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseInvoiceRelationshipModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseUserModel;
import com.xbongbong.saas.model.QuotationUserModel;
import com.xbongbong.saas.model.RefundUserModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.model.SupplierContactUserModel;
import com.xbongbong.saas.model.SupplierUserModel;
import com.xbongbong.saas.model.WarehouseUserModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFlowUserModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.service.ContractService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.DictionaryService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.saas.service.MarketActivityEffectService;
import com.xbongbong.saas.service.MobileDetailService;
import com.xbongbong.saas.service.OnlinePaymentFlowService;
import com.xbongbong.saas.service.OpportunityService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.ProductionOrderService;
import com.xbongbong.saas.service.QuotationService;
import com.xbongbong.saas.service.SaasListService;
import com.xbongbong.saas.service.SupplierService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WorkOrderFormService;
import com.xbongbong.saas.service.WorkReportService;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.FundSetHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.RoleEnum;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.SummaryUtil;
import com.xbongbong.workorder.service.WorkOrderFlowUserService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.join.query.HasChildQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import static com.xbongbong.saas.enums.RedundantTemplateTypeEnum.COMMUNICATE_PLAN;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 移动端详情基础信息获取
 *
 * @author GuoJun.HU
 * @date 2019/3/14 10:03
 * @since V1.0
 */
@Service("mobileDetailService")
public class MobileDetailServiceImpl implements MobileDetailService {
    private static final Logger LOG = LoggerFactory.getLogger(MobileDetailServiceImpl.class);
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private UserModel userModel;
    @Resource
    private SupplierService supplierService;
    @Resource
    private InventoryProductModel inventoryProductModel;
    @Resource
    private OpportunityFocusModel opportunityFocusModel;
    @Resource
    private OpportunityUserModel opportunityUserModel;
    @Resource
    private PurchaseUserModel purchaseUserModel;
    @Resource
    private SupplierUserModel supplierUserModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private ProductionOrderUserModel productionOrderUserModel;
    @Resource
    private BomUserModel bomUserModel;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    @Lazy
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private SaasGetHelp saasGetHelp;
    @Resource
    private ContractService contractService;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private WorkReportService workReportService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private ProGetHelp proGetHelp;
    @Resource
    private RefundUserModel refundUserModel;
    @Resource
    private PushLinkModel pushLinkModel;
    @Resource
    private MessageListService messageListService;
    @Resource
    private OpportunityService opportunityService;
    @Resource
    private CallCenterCommonService callCenterCommonService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private ProductionOrderService productionOrderService;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private WorkOrderFlowUserModel workOrderFlowUserModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private PaasCommentModel paasCommentModel;
    @Resource
    private LikeModel likeModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private FormHelp formHelp;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PushModel pushModel;
    @Resource
    private WorkOrderFlowUserService workOrderFlowUserService;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private SaasDetailPermissionHelp saasDetailPermissionHelp;
    @Resource
    private ProductService productService;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private UserHelp userHelp;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private QuotationUserModel quotationUserModel;
    @Resource
    private QuotationService quotationService;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private PaymentBalanceModel paymentBalanceModel;
    @Resource
    private ProDetailHandlerHelp proDetailHandlerHelp;
    @Resource
    private SaasListService saasListService;
    @Resource
    private PayBalanceModel payBalanceModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private FormDataValidateProductHelp formDataValidateProductHelp;
    @Resource
    private PurchaseInvoiceRelationshipModel purchaseInvoiceRelationshipModel;
    @Resource
    private InvoiceRelationshipModel invoiceRelationshipModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private InvoiceCommonHelper invoiceCommonHelper;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private PaymentTaskUserModel paymentTaskUserModel;
    @Resource
    private EsignHelp esignHelp;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private MarketActivityUserModel marketActivityUserModel;
    @Resource
    private ClueUserModel clueUserModel;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private PaasMenuService paasMenuService;
    @Resource
    private FundSetHelp fundSetHelp;
    @Resource
    private OnlinePaymentFlowService onlinePaymentFlowService;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private WorkOrderFormService workOrderFormService;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private MarketActivityEffectService marketActivityEffectService;
    @Resource
    private WarehouseUserModel warehouseUserModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private ContactUserModel contactUserModel;
    @Resource
    private SupplierContactUserModel supplierContactUserModel;
    @Resource
    private PaymentUserModel paymentUserModel;
    @Resource
    private PaymentSheetUserModel paymentSheetUserModel;
    @Resource
    private PayPlanSheetUserModel payPlanSheetUserModel;
    @Resource
    private PayPlanUserModel payPlanUserModel;
    @Resource
    private DetailTabDataPermissionHelp detailTabDataPermissionHelp;
    @Resource
    private PaasUserModel paasUserModel;

    @Resource
    private CommonDingtalkListQry commonDingtalkListQry;
    @Resource
    private ProcessFieldHelp processFieldHelp;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;

    /**
     * 通过业务类型获取简介中显示的字段
     *
     * @param businessType 业务类型
     * @return JSONArray
     * @author GuoJun.HU
     * @date 2019/3/12 17:23
     * @since V1.0
     */
    @Override
    public JSONArray getShowAttrList(Integer businessType) {
        MobileDetailSummaryEnum summaryEnum = MobileDetailSummaryEnum.getByCode(businessType);
        List<Object> attrList = summaryEnum.getAttrList();
        JSONArray resultArray = new JSONArray();
        for (Object object : attrList) {
            JSONObject itemObj = new JSONObject();
            itemObj.put("attr", ReflectHelper.valueGet(object, "attr"));
            itemObj.put("fieldType", ReflectHelper.valueGet(object, "fieldType"));
            itemObj.put("saasAttr", ReflectHelper.valueGet(object, "saasAttr"));
            resultArray.add(itemObj);
        }
        return resultArray;
    }

    @Override
//    public MobileDetailSpecialInfoPojo getMobileDetailSpecialInfo(PaymentSheetTypeEnum paymentSheetTypeEnum, String corpid, String userId, Integer businessType, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, Integer flowStatus) throws XbbException {
//        List<MobileDetailScriptPojo> scriptPojoList = getDetailShowScript(paymentSheetTypeEnum, businessType, data, explainMap, flowStatus);
//        MobileDetailStatusPojo mobileDetailStatusPojo = getDetailShowStatus(paymentSheetTypeEnum, businessType, data);
    public MobileDetailSpecialInfoPojo getMobileDetailSpecialInfo(SheetTypeEnum sheetTypeEnum, String corpid, UserVO loginUser, Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        JSONObject data = paasFormDataEntityExt.getData();
        String userId = loginUser.getUserId();
        Long dataId = paasFormDataEntityExt.getId();
        List<MobileDetailScriptPojo> scriptPojoList = getDetailShowScript(sheetTypeEnum,businessType, loginUser,paasFormDataEntityExt, explainMap);
        MobileDetailStatusPojo mobileDetailStatusPojo = getDetailShowStatus(sheetTypeEnum,businessType, data);
        Map<String, Object> operationList = getDetailShowOperation(corpid, userId, businessType, dataId, data);

        MobileDetailSpecialInfoPojo mobileDetailSpecialInfoPojo = new MobileDetailSpecialInfoPojo();
        mobileDetailSpecialInfoPojo.setScript(scriptPojoList);
        mobileDetailSpecialInfoPojo.setStatus(mobileDetailStatusPojo);
        mobileDetailSpecialInfoPojo.setOperation(operationList);
        if(XbbRefTypeEnum.checkScoreBusinessType(businessType)){
            mobileDetailSpecialInfoPojo.setScore(scoreRangeModel.getScoreShowValue(businessType,paasFormDataEntityExt));
        }
        return mobileDetailSpecialInfoPojo;
    }

    /**
     * 将summaryList中的数据字典/星级等key值存储的数据转换成value显示的数据
     *
     * @param corpid       公司的id
     * @param summaryList  需要转换的数据
     * @param businessType 业务类型
     * @author GuoJun.HU
     * @date 2019/3/13 16:16
     * @since V1.0
     */
    @Override
    public void transferKeyToShowValue(String corpid, List<SummaryDataPoJo> summaryList, Integer businessType) throws XbbException {
        // SaaS的数据字典需要特殊处理：将存储的key转成用于显示的value
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                /*for (SummaryDataPoJo summaryDataPoJo : summaryList) {
                    String attr = summaryDataPoJo.getAttr();
                    if (Objects.equals(attr, CustomerManagementEnum.IMPORTANT_DEGREE.getAttr())) {
                        List<Object> valueList = summaryDataPoJo.getValue();
                        if (!valueList.isEmpty()) {
                            Object valueKey = valueList.get(0);
                            Integer star = StringUtil.toInt(Objects.toString(valueKey), 0);
                            valueList.clear();
                            valueList.add(supplierService.transferLevel2Chinese(star));
                        }
                    }
                }*/
                Iterator<SummaryDataPoJo> customerIterator = summaryList.iterator();
                while (customerIterator.hasNext()){
                    SummaryDataPoJo item = customerIterator.next();
                    if (Objects.equals(item.getAttr(), CustomerManagementEnum.IMPORTANT_DEGREE.getAttr())) {
                        List<Object> valueList = item.getValue();
                        if (!valueList.isEmpty()) {
                            Object valueKey = valueList.get(0);
                            Integer star = StringUtil.toInt(Objects.toString(valueKey), 0);
                            if (Objects.equals(star,BasicConstant.ZERO)) {
                                // 星级为0不显示
                                customerIterator.remove();
                            }
                            valueList.clear();
                            valueList.add(supplierService.transferLevel2Chinese(star));
                        }
                    } else if (Objects.equals(item.getAttr(), CustomerManagementEnum.LAST_CONNECT_TIME.getAttr())) {
                        List<Object> valueList = item.getValue();
                        if (!valueList.isEmpty()) {
                            Object valueKey = valueList.get(0);
                            Long lastConnectTime = StringUtil.StringToLong(Objects.toString(valueKey), 0L);
                            valueList.clear();
                            valueList.add(DateTimeUtil.getLastConnectTimeStr(lastConnectTime));
                        }
                    }
                }
                break;
            case CONTACT:
                /*for (SummaryDataPoJo summaryDataPoJo : summaryList) {
                    String attr = summaryDataPoJo.getAttr();
                    if (Objects.equals(attr, ContactEnum.IMPORTANT_DEGREE.getAttr())) {
                        List<Object> valueList = summaryDataPoJo.getValue();
                        if (!valueList.isEmpty()) {
                            Object valueKey = valueList.get(0);
                            Integer star = StringUtil.toInt(Objects.toString(valueKey), 0);
                            valueList.clear();
                            valueList.add(supplierService.transferLevel2Chinese(star));
                        }
                    }
                }*/
                Iterator<SummaryDataPoJo> contactIterator = summaryList.iterator();
                while (contactIterator.hasNext()){
                    SummaryDataPoJo item = contactIterator.next();
                    if (Objects.equals(item.getAttr(), ContactEnum.IMPORTANT_DEGREE.getAttr())) {
                        List<Object> valueList = item.getValue();
                        if (!valueList.isEmpty()) {
                            Object valueKey = valueList.get(0);
                            Integer star = StringUtil.toInt(Objects.toString(valueKey), 0);
                            if (Objects.equals(star, BasicConstant.ZERO)) {
                                // 星级为0不显示
                                contactIterator.remove();
                            }
                            valueList.clear();
                            valueList.add(supplierService.transferLevel2Chinese(star));
                        }
                    }
                }
                break;
            case SUPPLIER:
                for (SummaryDataPoJo summaryDataPoJo : summaryList) {
                    String attr = summaryDataPoJo.getAttr();
                    if (Objects.equals(attr, SupplierEnum.QUALITY_STANDARD.getAttr()) || Objects.equals(attr, SupplierEnum.SUPPLY_COST.getAttr())
                            || Objects.equals(attr, SupplierEnum.DELIVERY_CAPACITY.getAttr()) || Objects.equals(attr, SupplierEnum.SERVER_CAPACITY.getAttr())
                            || Objects.equals(attr, SupplierEnum.CREDIT_LEVEL.getAttr())) {
                        List<Object> valueList = summaryDataPoJo.getValue();
                        if (!valueList.isEmpty()) {
                            Object valueKey = valueList.get(0);
                            valueList.clear();
                            valueList.add(supplierService.getLevelString(Objects.toString(valueKey)));
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * Description:
     * @param corpid
     * @param summaryList
     * @param businessType
     * @author 刘阳
     * @date 2019/7/6 1:56 PM
     * @since v1.0
     */
    @Override
    public void specialTransferKeyToShowValue(String corpid, List<SummaryDataPoJo> summaryList, Integer businessType, JSONObject data, Long formId) throws XbbException{
        //方便前端显示，把负责人拼接成一个
        // 已经在com.xbongbong.paas.util.ExplainUtil.getSpecialSummaryList解析了，这里没必要存在了 @date 2022/2/15 9:31
//        for (SummaryDataPoJo poJo : summaryList) {
//            if (Objects.equals(poJo.getAttr(), "ownerId") || Objects.equals(poJo.getAttrName(), I18nMessageUtil.getMessage(CommonConstant.COLLABORATOR))) {
//                List<Object> value = poJo.getValue();
//                if (value.size() > 0) {
//                    String userName = "";
//                    List<Object> list = new ArrayList<>();
//                    StringBuilder stringBuilder1 = new StringBuilder();
//                    for (Object object : value) {
//                        StringBuilder stringBuilder = new StringBuilder();
//                        stringBuilder.append(object.toString());
//                        String s = stringBuilder.toString() + "、";
//                        stringBuilder1.append(s);
//                    }
//                    userName = stringBuilder1.toString();
//                    if (userName.length() > 0) {
//                        userName = userName.substring(0,userName.length()-1);
//                    }
//                    list.add(userName);
//                    poJo.setValue(list);
//                }
//            }
            // // 标签设置
//            if (Objects.equals(poJo.getFieldType(), FieldTypeEnum.LABEL.getType())){
//                JSONArray jsonArray = data.getJSONArray(poJo.getAttr());
//                if(Objects.nonNull(jsonArray) && CollectionsUtil.isNotEmpty(jsonArray)){
//                    List<Long> longs = new ArrayList<>();
//                    try {
//                        List<LabelPojo> labelPojos = JSON.parseArray(jsonArray.toJSONString(), LabelPojo.class);
//                        for (LabelPojo item : labelPojos) {
//                            if (Objects.isNull(item.getTabelType()) || Objects.equals(item.getTabelType(),BasicConstant.ZERO)) {
//                                longs.add(item.getId());
//                            }
//                        }
//                    } catch (Exception e) {
//                        longs = JSON.parseArray(jsonArray.toJSONString(), Long.class);
//                    }
//                    List<Object> value = new ArrayList<>();
//                    if (longs != null && longs.size() > 0) {
//                        List<LabelEntity> byLabelIds = labelModel.getByLabelIds(longs, corpid);
//                        byLabelIds.forEach(item ->value.add(item.getName()));
//                    }
//                    poJo.setValue(value);
//                }
//            }
//        }
        // SaaS的数据字典需要特殊处理：将存储的key转成用于显示的value
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case SALES_OPPORTUNITY:

                for ( SummaryDataPoJo summaryDataPoJo : summaryList ) {
                    String attr = summaryDataPoJo.getAttr();
                    if ( Objects.equals(attr, SalesOpportunityEnum.ESTIMATE_END_TIME.getAttr()) ) {
                        List<Object> valueList = summaryDataPoJo.getValue();
                        if ( valueList.isEmpty() ) {
                            break;
                        }
                        String valueKey = (String) valueList.get(0);
                        Long estimate = DateTimeUtil.getInt(valueKey, DateTimeUtil.SDFDate);
                        if ( estimate < DateTimeUtil.getTodayInt() ) {
                            String nameOrCode = data.getString(SalesOpportunityEnum.SALE_STAGE.getAttr());
                            SaleStageEntity saleStage = null;
                            if (StringUtil.isNotEmpty(nameOrCode)) {
                                saleStage = saleStageModel.getByCode(corpid, formId, nameOrCode);
                            }
                            List<Integer> noRemindCode = Arrays.asList(StageTypeEnum.SUCCESS_STAGE.getType(),StageTypeEnum.FAIL_STAGE.getType(),StageTypeEnum.CANCEL_STAGE.getType());
                            if(Objects.isNull(saleStage) || !noRemindCode.contains(saleStage.getType())) {
                                // 预计结束时间延期标红
                                summaryDataPoJo.setStatus("delay");
                            }
                        }
                        break;
                    }
                }
                break;
            case PAYMENT:
                /**
                 * 资金改造一期，需要处理移动端详情页面的预计回款日期标红
                 * (预计回款日期大于等于今日的还未回款或部分回款的应收款)
                 * @author chenshan
                 * @Date 2019-11-06 13:53
                 */
                String status = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getAlias());
                if ( Objects.equals(status, PaymentStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(status, PaymentStatusEnum.PARTIAL_RECEIPTS.getCode()) ) {
                    for ( SummaryDataPoJo summaryDataPoJo : summaryList ) {
                        String attr = summaryDataPoJo.getAttr();
                        if ( Objects.equals(attr, PaymentEnum.ESTIMATE_TIME.getAttr()) ) {
                            List<Object> valueList = summaryDataPoJo.getValue();
                            if ( valueList.isEmpty() ) {
                                break;
                            }
                            String valueKey = (String) valueList.get(0);
                            Long estimate = DateTimeUtil.getInt(valueKey, DateTimeUtil.SDFDate);
                            if ( estimate < DateTimeUtil.getTodayInt() ) {
                                summaryDataPoJo.setStatus("delay");
                            }
                            break;
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 处理summaryList中需要特殊处理的字段
     * 比如：回款关联的合同要支持点击跳转
     * 比如：地址字段要支持点击跳转等
     *
     * @param corpid                公司的id
     * @param summaryList           需要转换的数据
     * @param businessType          业务类型
     * @param data                  表单数据
     * @param formDataId            表单数据id
     * @param paasFormDataEntityExt 表单数据扩展
     * @throws XbbException XbbException
     * @author GuoJun.HU
     * @date 2019/3/13 16:16
     * @since V1.0
     */
    @Override
    public List<PaasFormDataEntityExt> handleSummarySpecialAttr(String corpid, List<SummaryDataPoJo> summaryList, Integer businessType, JSONObject data, Long formDataId, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        List<PaasFormDataEntityExt> childProductESList = new ArrayList<>();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case CONTRACT:
                SummaryDataPoJo signerSummary = getSummaryDataPoJoByAttr(summaryList, ContractEnum.SIGN_PERSON.getAttr());
                if (Objects.nonNull(signerSummary)) {
                    List<Object> values = signerSummary.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        signerSummary.setValue(values);
                    }
                }
                break;
            case SALES_OPPORTUNITY:
                for (SummaryDataPoJo summaryItem : summaryList) {
                    if (Objects.equals(summaryItem.getAttr(), FieldTypeEnum.SERIALNO.getAlias())) {
                        summaryItem.setAttrName(SalesOpportunityEnum.SERIAL_NO.getAttrName());
                    }
                }
                break;
            case PAYMENT:
                SummaryDataPoJo contractSummary = getSummaryDataPoJoByAttr(summaryList, PaymentEnum.CONTRACT_LINK_TEXT.getAttr());
                if (Objects.nonNull(contractSummary)) {
                    contractSummary.setAttrName(PaymentEnum.CONTRACT.getAttrName());
                    Long dataId = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentEnum.CONTRACT.getAttr(), 0L);
                    contractSummary.setDirectExtra(dataId, RedundantTemplateTypeEnum.CONTRACT.getCode());
                }
                break;
            case PAY_PLAN:
                SummaryDataPoJo purchaseSummary = getSummaryDataPoJoByAttr(summaryList, PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr());
                if (Objects.nonNull(purchaseSummary)) {
                    purchaseSummary.setAttrName(PayPlanEnum.LINK_PURCHASE.getAttrName());
                    Long dataId = FastJsonHelper.getLongOrDefaultFromFormData(data, PayPlanEnum.LINK_PURCHASE.getAttr(), 0L);
                    purchaseSummary.setDirectExtra(dataId, RedundantTemplateTypeEnum.PURCHASE.getCode());
                }
                break;
            case CONTACT:
                SummaryDataPoJo contactSummary = getSummaryDataPoJoByAttr(summaryList, ContactEnum.PHONE.getAttr());
                if (Objects.nonNull(contactSummary)) {
                    JSONArray phoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ContactEnum.PHONE.getAttr(), new JSONArray());
                    List<Object> phoneList = new ArrayList<>();
                    phoneArray.forEach(phoneItem -> {
                        Object phoneNum = ((JSONObject) phoneItem).get("text_2");
                        if (Objects.nonNull(phoneNum)) {
                            phoneList.add(phoneNum);
                        }
                    });
                    contactSummary.setValue(phoneList);
                    contactSummary.setPhoneExtra();
                }
                break;
            case SUPPLIER_CONTACT:
                SummaryDataPoJo supplierContactSummary = getSummaryDataPoJoByAttr(summaryList, SupplierContactEnum.PHONE.getAttr());
                if (Objects.nonNull(supplierContactSummary)) {
                    JSONArray phoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, SupplierContactEnum.PHONE.getAttr(), new JSONArray());
                    List<Object> phoneList = new ArrayList<>();
                    phoneArray.forEach(phoneItem -> {
                        Object phoneNum = ((JSONObject) phoneItem).get("text_2");
                        if (Objects.nonNull(phoneNum)) {
                            phoneList.add(phoneNum);
                        }
                    });
                    supplierContactSummary.setValue(phoneList);
                    supplierContactSummary.setPhoneExtra();
                }
                break;
            case PRODUCT:
                SummaryDataPoJo imageSummary = getSummaryDataPoJoByAttr(summaryList, ProductEnum.PRODUCT_IMGS.getAttr());
                if (Objects.nonNull(imageSummary)) {
                    JSONArray imageArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray());
                    imageSummary.setValue(imageArray);
                    imageSummary.setImageExtra();
                }

                SummaryDataPoJo specSummary = getSummaryDataPoJoByAttr(summaryList, ProductEnum.SPECIFICATION.getAttr());
                SummaryDataPoJo priceSummary = getSummaryDataPoJoByAttr(summaryList, ProductEnum.PRICE.getAttr());
                SummaryDataPoJo costSummary = getSummaryDataPoJoByAttr(summaryList, ProductEnum.COST.getAttr());
                String spec4Show;
                if (Objects.nonNull(specSummary) || Objects.nonNull(priceSummary) || Objects.nonNull(costSummary)) {
                    childProductESList = productService.getDataByParentId(corpid, formDataId);
                }
                String price4Show;
                PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(businessType, corpid);
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
                FieldAttrEntity priceAttrEntity = explainMap.get(ProductEnum.PRICE.getAttr());
                if (!childProductESList.isEmpty()) {
                    // 是否是多单位
                    boolean enableMultiUnit = Objects.equals(childProductESList.get(0).getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), BasicConstant.ONE);
                    List<PaasFormDataEntityExt> multiProductList = new ArrayList<>();
                    Map<Long, Object> multiProductsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if (enableMultiUnit && Objects.nonNull(priceSummary)) {
                        Long parentId = childProductESList.get(0).getData().getLong(ProductEnum.PARENT_ID.getAttr());
                        productService.handleMultiPrice(multiProductsMap, multiProductList,corpid, parentId, priceAttrEntity.getAccuracy());
                    }

                    if (childProductESList.size() > 1) {
                        spec4Show = String.format(I18nMessageUtil.getMessage(StringConstant.SPEC_NUM_FORMAT), childProductESList.size());
                        if (enableMultiUnit) {
                            price4Show = productService.getPriceOrCostRegion(multiProductList, ProductEnum.PRICE.getAttr(), priceAttrEntity.getAccuracy());
                        }else {
                            Double min = getDoubleOrDefaultFromFormData(childProductESList.get(0).getData(), ProductEnum.PRICE.getAttr(), 0D);
                            Double max = getDoubleOrDefaultFromFormData(childProductESList.get(childProductESList.size() - 1).getData(), ProductEnum.PRICE.getAttr(), 0D);
                            if (Objects.equals(Double.compare(min, max), 0)) {
                                price4Show = AttrDecimalPrecisionHelper.parseThousandth(min, priceAttrEntity.getAccuracy()).toString();
                            } else {
                                price4Show = String.format(StringConstant.PRICE_RANFE, AttrDecimalPrecisionHelper.parseThousandth(min, priceAttrEntity.getAccuracy()), AttrDecimalPrecisionHelper.parseThousandth(max, priceAttrEntity.getAccuracy()));
                            }
                        }
                    } else {
                        PaasFormDataEntityExt paasFormDataEsEntity = childProductESList.get(0);
                        JSONObject childProductObj = paasFormDataEsEntity.getData();
                        // 是否是多规格
                        Integer advancedMode = getIntegerOrDefaultFromFormData(childProductObj, ProductEnum.SPECIFICATION.getAttr(), 0);
                        boolean multiSpec = Objects.equals(advancedMode, 1);
                        // 如果是多规格的产品但是只有一个子产品或者是单规格产品则显示唯一的子产品规格
                        spec4Show = FastJsonHelper.getStringOrDefaultFromFormData(childProductObj, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                        if (multiSpec) {
                            spec4Show = specificationModel.joinSpecification(spec4Show);
                        }
                        price4Show = FastJsonHelper.getStringOrDefaultFromFormData(childProductObj, ProductEnum.PRICE.getAttr(), "");
                        if (!price4Show.isEmpty()) {
                            if (enableMultiUnit) {
                                price4Show = productService.getPriceOrCostRegion(multiProductList, ProductEnum.PRICE.getAttr(), priceAttrEntity.getAccuracy());
                            }else {
                                price4Show = (String) AttrDecimalPrecisionHelper.parseThousandth(Double.parseDouble(price4Show), priceAttrEntity.getAccuracy());
                            }
                        }
                    }

                    if (Objects.nonNull(specSummary)) {
                        specSummary.setValue(Collections.singletonList(spec4Show));
                    }

                    if (Objects.nonNull(priceSummary)) {
                        priceSummary.setValue(Collections.singletonList(price4Show));
                    }
                }

                if (Objects.nonNull(costSummary) && !childProductESList.isEmpty()) {
                    Object cost = productService.getCostBySummary(childProductESList, corpid, formDataId);
                    costSummary.setValue(Collections.singletonList(cost));
                }
                break;
            case RETURNED_PURCHASE:
                SummaryDataPoJo purchaseLinkSummary = getSummaryDataPoJoByAttr(summaryList, ReturnedPurchaseEnum.PURCHASE_SHEET_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(purchaseLinkSummary)) {
                    purchaseLinkSummary.setAttrName(ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttrName());
                    Long dataId = FastJsonHelper.getLongOrDefaultFromFormData(data, ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr(), 0L);
                    purchaseLinkSummary.setDirectExtra(dataId, RedundantTemplateTypeEnum.PURCHASE.getCode());
                }
                break;
            case WAREHOUSE:
                SummaryDataPoJo addressSummary = getSummaryDataPoJoByAttr(summaryList, WarehouseEnum.ADDRESS.getAttr());
                if (Objects.nonNull(addressSummary)) {
                    List<Object> values = addressSummary.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        addressSummary.setValue(values);
                    }
                    Double latitude = getDoubleOrDefaultFromFormData(data, WarehouseEnum.LATITUDE.getAttr(), 0D);
                    Double longitude = getDoubleOrDefaultFromFormData(data, WarehouseEnum.LONGITUDE.getAttr(), 0D);
                    addressSummary.setAddressExtra(latitude, longitude);
                }

                SummaryDataPoJo managerSummary = getSummaryDataPoJoByAttr(summaryList, WarehouseEnum.MANAGER_ID.getAttr());
                if (Objects.nonNull(managerSummary)) {
                    List<Object> values = managerSummary.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        managerSummary.setValue(values);
                    }
                }
                break;
            case ASSEMBLE:
                SummaryDataPoJo outAssembleSummary = getSummaryDataPoJoByAttr(summaryList, AssembleEnum.OUT_WAREHOUSE_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(outAssembleSummary)) {
                    outAssembleSummary.setAttrName(AssembleEnum.OUT_WAREHOUSE_ID.getAttrName());
                }
                SummaryDataPoJo inAssembleSummary = getSummaryDataPoJoByAttr(summaryList, AssembleEnum.INTO_WAREHOUSE_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(inAssembleSummary)) {
                    inAssembleSummary.setAttrName(AssembleEnum.INTO_WAREHOUSE_ID.getAttrName());
                }

                SummaryDataPoJo assembleManage = getSummaryDataPoJoByAttr(summaryList, AssembleEnum.MANAGER_ID.getAttr());
                if (Objects.nonNull(assembleManage)) {
                    List<Object> values = assembleManage.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        assembleManage.setValue(values);
                    }
                }
                break;
            case TRANSFER:
                SummaryDataPoJo outTransferSummary = getSummaryDataPoJoByAttr(summaryList, TransferEnum.OUT_WAREHOUSE_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(outTransferSummary)) {
                    outTransferSummary.setAttrName(TransferEnum.OUT_WAREHOUSE_ID.getAttrName());
                }
                SummaryDataPoJo inTransferSummary = getSummaryDataPoJoByAttr(summaryList, TransferEnum.INTO_WAREHOUSE_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(inTransferSummary)) {
                    inTransferSummary.setAttrName(TransferEnum.INTO_WAREHOUSE_ID.getAttrName());
                }

                SummaryDataPoJo transferManage = getSummaryDataPoJoByAttr(summaryList, TransferEnum.MANAGER_NAME.getAttr());
                if (Objects.nonNull(transferManage)) {
                    List<Object> values = transferManage.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        transferManage.setValue(values);
                    }
                }
                break;
            case INVENTORY:
                SummaryDataPoJo inventorySummary = getSummaryDataPoJoByAttr(summaryList, InventoryEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(inventorySummary)) {
                    inventorySummary.setAttrName(InventoryEnum.WAREHOUSE_ID.getAttrName());
                }
                SummaryDataPoJo productSummary = getSummaryDataPoJoByAttr(summaryList, InventoryEnum.PRODUCT.getAttr());
                if (Objects.nonNull(productSummary)) {
                    int winTypeNum = 0;
                    int lostTypeNum = 0;
                    double winProductNum = 0D;
                    double lostProductNum = 0D;
                    List<InventoryProductEntity> linkProductList = inventoryProductModel.getProductsByInventoryId(formDataId, corpid);
                    for (InventoryProductEntity linkProduct : linkProductList) {
                        if (linkProduct.getOriNum() > linkProduct.getProductNum()) {
                            // 账面数量超过实际数量  盘亏
                            lostTypeNum++;
                            double lostNum = Arith.sub(linkProduct.getOriNum(), linkProduct.getProductNum());
                            lostProductNum = Arith.add(lostProductNum, lostNum);
                        }
                        if (linkProduct.getOriNum() < linkProduct.getProductNum()) {
                            //盘盈
                            winTypeNum++;
                            double winNum = Arith.sub(linkProduct.getProductNum(), linkProduct.getOriNum());
                            winProductNum = Arith.add(winProductNum, winNum);
                        }
                    }
                    String winStr = "0", lostStr = "0";
                    if (winTypeNum > 0) {
                        winStr = String.format(I18nMessageUtil.getMessage(StringConstant.PRODUCT_TYPE_NUM), winTypeNum, winProductNum);
                    }
                    productSummary.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.INVENTORY_SURPLUS));
                    productSummary.setValue(Collections.singletonList(winStr));
                    if (lostTypeNum > 0) {
                        lostStr = String.format(I18nMessageUtil.getMessage(StringConstant.PRODUCT_TYPE_NUM), lostTypeNum, lostProductNum);
                    }
                    SummaryDataPoJo lostPojo = new SummaryDataPoJo();
                    lostPojo.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.INVENTORY_LOSSES));
                    lostPojo.setValue(Collections.singletonList(lostStr));
                    summaryList.add(0, lostPojo);
                }

                SummaryDataPoJo inventoryManage = getSummaryDataPoJoByAttr(summaryList, InventoryEnum.MANAGER_ID.getAttr());
                if (Objects.nonNull(inventoryManage)) {
                    List<Object> values = inventoryManage.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        inventoryManage.setValue(values);
                    }
                }
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                SummaryDataPoJo refSummary = getSummaryDataPoJoByAttr(summaryList, InstockEnum.REF_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(refSummary)) {
                    refSummary.setAttrName(InstockEnum.REF_ID.getAttrName());
                    Long refId = FastJsonHelper.getLongOrDefaultFromFormData(data, InstockEnum.REF_ID.getAttr(), 0L);
                    Integer refType = getIntegerOrDefaultFromFormData(data, InstockEnum.TYPE.getAttr(), 0);
                    InstockTypeEnum typeEnum = InstockTypeEnum.getByCode(refType);
                    refSummary.setDirectExtra(refId, typeEnum.getBusinessType());
                }
                SummaryDataPoJo warehouseSummary = getSummaryDataPoJoByAttr(summaryList, InstockEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(warehouseSummary)) {
                    warehouseSummary.setAttrName(InstockEnum.WAREHOUSE_ID.getAttrName());
                }

                SummaryDataPoJo instockManage = getSummaryDataPoJoByAttr(summaryList, InstockEnum.MANAGER_ID.getAttr());
                if (Objects.nonNull(instockManage)) {
                    List<Object> values = instockManage.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        instockManage.setValue(values);
                    }
                }
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                SummaryDataPoJo refOutstockSummary = getSummaryDataPoJoByAttr(summaryList, OutstockEnum.REF_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(refOutstockSummary)) {
                    refOutstockSummary.setAttrName(OutstockEnum.REF_ID.getAttrName());
                    Long refId = FastJsonHelper.getLongOrDefaultFromFormData(data, OutstockEnum.REF_ID.getAttr(), 0L);
                    Integer refType = getIntegerOrDefaultFromFormData(data, OutstockEnum.TYPE.getAttr(), 0);
                    OutstockTypeEnum typeEnum = OutstockTypeEnum.getByCode(refType);
                    refOutstockSummary.setDirectExtra(refId, typeEnum.getBusinessType());
                }
                SummaryDataPoJo warehouseOutstockSummary = getSummaryDataPoJoByAttr(summaryList, OutstockEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr());
                if (Objects.nonNull(warehouseOutstockSummary)) {
                    warehouseOutstockSummary.setAttrName(OutstockEnum.WAREHOUSE_ID.getAttrName());
                }

                SummaryDataPoJo outstockManage = getSummaryDataPoJoByAttr(summaryList, OutstockEnum.MANAGER_ID.getAttr());
                if (Objects.nonNull(outstockManage)) {
                    List<Object> values = outstockManage.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {

                        outstockManage.setValue(values);
                    }
                }
                break;
            case PRODUCTIONORDER:
                SummaryDataPoJo outOrderSummary = getSummaryDataPoJoByAttr(summaryList, ProductionOrderEnum.OUT_WAREHOUSE_ID_LINK_TEXT.getAttr());
                if (Objects.nonNull(outOrderSummary)) {
                    outOrderSummary.setAttrName(ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttrName());
                }
                SummaryDataPoJo inOrderSummary = getSummaryDataPoJoByAttr(summaryList, ProductionOrderEnum.INTO_WAREHOUSE_ID_LINK_TEXT.getAttr());
                if (Objects.nonNull(inOrderSummary)) {
                    inOrderSummary.setAttrName(ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttrName());
                }
                break;
            case WORKREPORT:
                SummaryDataPoJo reportSummary = getSummaryDataPoJoByAttr(summaryList, WorkReportFieldEnum.CC.getAttr());
                if (Objects.nonNull(reportSummary)) {
                    List<Object> values = reportSummary.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        reportSummary.setValue(values);
                    }
                }
                SummaryDataPoJo workReportMemo = getSummaryDataPoJoByAttr(summaryList, WorkReportFieldEnum.CONTENT.getAttr());
                if (Objects.nonNull(workReportMemo)) {
                    workReportMemo.setMemo();
                }
                break;
            case COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                SummaryDataPoJo communicateImageSummary = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.IMAGES.getAttr());
                if (Objects.nonNull(communicateImageSummary)) {
                    JSONArray imageArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerCommunicateEnum.IMAGES.getAttr(), new JSONArray());
                    communicateImageSummary.setValue(imageArray);
                    communicateImageSummary.setImageExtra();
                }
                String communicateUserName = "";
                SummaryDataPoJo userSummary = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.USER_NAME.getAttr());
                if (Objects.isNull(userSummary) && Objects.nonNull(paasFormDataEntityExt)) {
                    communicateUserName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_NAME.getAttr(), "");
                    SummaryDataPoJo userNameSummary = new SummaryDataPoJo();
                    userNameSummary.setAttr(CustomerCommunicateEnum.USER_NAME.getAttr());
                    userNameSummary.setSaasAttr(CustomerCommunicateEnum.USER_NAME.getSaasAttr());
                    userNameSummary.setAttrName(CustomerCommunicateEnum.USER_NAME.getAttrName());
                    userNameSummary.setValue(Collections.singletonList(communicateUserName));

                    //老数据存的string,现在变成list,故进行判断
                    SummaryDataPoJo userAvatarSummary = new SummaryDataPoJo();
                    if (data.containsKey(CustomerCommunicateEnum.USER_AVATAR.getAttr())) {
                        Object object = data.get(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        if (object != null) {
                            if (object instanceof String) {
                                String userAvatar = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr(), "");
                                userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                                userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                                userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                                userAvatarSummary.setValue(Collections.singletonList(userAvatar));
                            } else {
                                List<Object> userAvatar = saasUpdateHelp.getListFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr());
                                userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                                userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                                userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                                userAvatarSummary.setValue(userAvatar);
                            }
                        }
                    }

                    summaryList.add(0, userNameSummary);
                    summaryList.add(0, userAvatarSummary);
                }

                SummaryDataPoJo communicateTime = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr());
                if (Objects.nonNull(communicateTime)) {
                    Long crmCommunicateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
                    if (!Objects.equals(crmCommunicateTime, 0L)) {
                        communicateTime.setValue(Collections.singletonList(DateTimeUtil.getStringEpochSecond(crmCommunicateTime, DateTimeUtil.SDFMDHM)));
                    }
                }
                SummaryDataPoJo communicateContact = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr());
                if (Objects.nonNull(communicateContact)) {
                    JSONArray contactArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr(), new JSONArray());
                    if (contactArr != null && !contactArr.isEmpty()) {
                        StringBuilder name = new StringBuilder();
                        for (int i = 0; i < contactArr.size(); i++) {
                            String contact = contactArr.getString(i);
                            name.append(contact).append("、");
                        }
                        // 去掉最后的"、"号
                        String subStringName = name.toString().substring(0, name.length() - 1);
                        communicateContact.setValue(Collections.singletonList(subStringName));
                    }
                }
                SummaryDataPoJo customerNamePojo = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
                SummaryDataPoJo communicateAddress = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.ADDRESS.getAttr());
                if (Objects.nonNull(communicateAddress)) {
                    List<Object> values = communicateAddress.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty() && Objects.nonNull(values.get(0))) {
                        JSONObject addressObj = (JSONObject) values.get(0);
                        String province = addressObj.getString(AddressEnum.PROVINCE.getAlias());
                        String city = addressObj.getString(AddressEnum.CITY.getAlias());
                        String district = addressObj.getString(AddressEnum.DISTRICT.getAlias());
                        String address = addressObj.getString(AddressEnum.ADDRESS.getAlias());
                        StringBuilder detailAddress = new StringBuilder();
                        detailAddress.append(province).append(city).append(district).append(address);
                        communicateAddress.setValue(Collections.singletonList(detailAddress));

                        JSONObject locationJsonObj = addressObj.getJSONObject("location");
                        Double lon = 0D;
                        Double lat = 0D;
                        if (locationJsonObj != null) {
                            lon = locationJsonObj.getDouble("lon");
                            lat = locationJsonObj.getDouble("lat");
                        }
                        String customerName = "";
                        if (Objects.nonNull(customerNamePojo)) {
                            List<Object> customerNameValues = customerNamePojo.getValue();
                            if (Objects.nonNull(customerNameValues) && !customerNameValues.isEmpty()) {
                                customerName = (String) customerNameValues.get(0);
                            }
                        }
                        String title = communicateUserName + I18nMessageUtil.getMessage(I18nStringConstant.FOLLOW_UP_CUSTOMERS) + customerName;
                        communicateAddress.setAddressExtra(lat, lon, title);
                    }
                }
                break;
            case JXC_COMMUNICATE:
                SummaryDataPoJo communicateJxcImageSummary = getSummaryDataPoJoByAttr(summaryList, SupplierCommunicateEnum.IMAGES.getAttr());
                if (Objects.nonNull(communicateJxcImageSummary)) {
                    JSONArray imageArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, SupplierCommunicateEnum.IMAGES.getAttr(), new JSONArray());
                    communicateJxcImageSummary.setValue(imageArray);
                    communicateJxcImageSummary.setImageExtra();
                }
                String userName = "";
                SummaryDataPoJo userJxcSummary = getSummaryDataPoJoByAttr(summaryList, SupplierCommunicateEnum.USER_NAME.getAttr());
                if (Objects.isNull(userJxcSummary) && Objects.nonNull(paasFormDataEntityExt)) {
                    userName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), SupplierCommunicateEnum.USER_NAME.getAttr(), "");
                    SummaryDataPoJo userNameSummary = new SummaryDataPoJo();
                    userNameSummary.setAttr(SupplierCommunicateEnum.USER_NAME.getAttr());
                    userNameSummary.setSaasAttr(SupplierCommunicateEnum.USER_NAME.getSaasAttr());
                    userNameSummary.setAttrName(SupplierCommunicateEnum.USER_NAME.getAttrName());
                    userNameSummary.setValue(Collections.singletonList(userName));

                    //老数据存的string,现在变成list,故进行判断
                    SummaryDataPoJo userAvatarSummary = new SummaryDataPoJo();
                    if (data.containsKey(CustomerCommunicateEnum.USER_AVATAR.getAttr())) {
                        Object object = data.get(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        if (object != null) {
                            if (object instanceof String) {
                                String userAvatar = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr(), "");
                                userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                                userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                                userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                                userAvatarSummary.setValue(Collections.singletonList(userAvatar));
                            } else {
                                List<Object> userAvatar = saasUpdateHelp.getListFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr());
                                userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                                userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                                userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                                userAvatarSummary.setValue(userAvatar);
                            }
                        }
                    }

                    summaryList.add(0, userNameSummary);
                    summaryList.add(0, userAvatarSummary);
                }

                SummaryDataPoJo jxcCommunicateTimePojo = getSummaryDataPoJoByAttr(summaryList, SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr());
                if (Objects.nonNull(jxcCommunicateTimePojo)) {
                    Long jxcCommunicateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
                    if (!Objects.equals(jxcCommunicateTime, 0L)) {
                        jxcCommunicateTimePojo.setValue(Collections.singletonList(DateTimeUtil.getStringEpochSecond(jxcCommunicateTime, DateTimeUtil.SDFMDHM)));
                    }
                }
                SummaryDataPoJo supplierNamePojo = getSummaryDataPoJoByAttr(summaryList, SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr());
                SummaryDataPoJo jxcCommunicateAddress = getSummaryDataPoJoByAttr(summaryList, SupplierCommunicateEnum.ADDRESS.getAttr());
                if (Objects.nonNull(jxcCommunicateAddress)) {
                    List<Object> values = jxcCommunicateAddress.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        JSONObject addressObj = (JSONObject) values.get(0);
                        String province = addressObj.getString(AddressEnum.PROVINCE.getAlias());
                        String city = addressObj.getString(AddressEnum.CITY.getAlias());
                        String district = addressObj.getString(AddressEnum.DISTRICT.getAlias());
                        String address = addressObj.getString(AddressEnum.ADDRESS.getAlias());
                        StringBuilder detailAddress = new StringBuilder();
                        detailAddress.append(province).append(city).append(district).append(address);
                        jxcCommunicateAddress.setValue(Collections.singletonList(detailAddress));

                        JSONObject locationJsonObj = addressObj.getJSONObject("location");
                        Double lon = 0D;
                        Double lat = 0D;
                        if (locationJsonObj != null) {
                            lon = locationJsonObj.getDouble("lon");
                            lat = locationJsonObj.getDouble("lat");
                        }
                        String supplierName = "";
                        if (Objects.nonNull(supplierNamePojo)) {
                            List<Object> supplierNameValues = supplierNamePojo.getValue();
                            if (Objects.nonNull(supplierNameValues) && !supplierNameValues.isEmpty()) {
                                supplierName = (String) supplierNameValues.get(0);
                            }
                        }
                        String title = userName + I18nMessageUtil.getMessage(I18nStringConstant.FOLLOW_UP_WITH_SUPPLIERS) + supplierName;
                        jxcCommunicateAddress.setAddressExtra(lat, lon, title);
                    }
                }
                SummaryDataPoJo jxcCommunicateContact = getSummaryDataPoJoByAttr(summaryList, SupplierCommunicateEnum.SUPPLIER_CONTACT_NAME_LINK_TEXT.getAttr());
                if (Objects.nonNull(jxcCommunicateContact)) {
                    JSONArray contactArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, SupplierCommunicateEnum.SUPPLIER_CONTACT_NAME_LINK_TEXT.getAttr(), new JSONArray());
                    if (contactArr != null && !contactArr.isEmpty()) {
                        StringBuilder name = new StringBuilder();
                        for (int i = 0; i < contactArr.size(); i++) {
                            String contact = contactArr.getString(i);
                            name.append(contact).append("、");
                        }
                        // 去掉最后的"、"号
                        String subStringName = name.toString().substring(0, name.length() - 1);
                        jxcCommunicateContact.setValue(Collections.singletonList(subStringName));
                    }
                }
                break;
            case COMMUNICATE_PLAN:
                SummaryDataPoJo creatorSummary = getSummaryDataPoJoByAttr(summaryList, CommunicatePlanEnum.CREATOR_ID.getAttr());
                if (Objects.nonNull(creatorSummary) && Objects.nonNull(paasFormDataEntityExt)) {
                    creatorSummary.setAttr(CommunicatePlanEnum.CREATOR_ID.getAttr());
                    creatorSummary.setSaasAttr(CommunicatePlanEnum.CREATOR_ID.getSaasAttr());
                    creatorSummary.setAttrName(CommunicatePlanEnum.CREATOR_ID.getAttrName());
                    creatorSummary.setFieldType(CommunicatePlanEnum.CREATOR_ID.getFieldType());
                    // 系统生成的访客计划（智能助手）
                    String creatorName;
                    if(Objects.equals(PaasConstant.SYS_USER_ID, paasFormDataEntityExt.getCreatorId())) {
                        creatorName = I18nMessageUtil.getMessage(PaasConstant.SYS_GENERATED);
                    } else {
                        UserEntity userEntity = userModel.getByKey(paasFormDataEntityExt.getCreatorId(), corpid);
                        creatorName = Objects.isNull(userEntity) ? "" : Objects.toString(userEntity.getName(), "");
                    }
                    creatorSummary.setValue(Collections.singletonList(creatorName));
                }
                break;
            case WORKORDER:
                SummaryDataPoJo workOrderSummary = getSummaryDataPoJoByAttr(summaryList, WorkOrderEnum.ADDRESS.getAttr());
                if (Objects.nonNull(workOrderSummary)) {
                    List<Object> values = workOrderSummary.getValue();
                    if (Objects.nonNull(values) && !values.isEmpty()) {
                        workOrderSummary.setValue(values);
                    }
                    Double latitude = getDoubleOrDefaultFromFormData(data, WarehouseEnum.LATITUDE.getAttr(), 0D);
                    Double longitude = getDoubleOrDefaultFromFormData(data, WarehouseEnum.LONGITUDE.getAttr(), 0D);
                    workOrderSummary.setAddressExtra(latitude, longitude);
                }
                break;
            case PAYMENT_TASK:
                SummaryDataPoJo paymentTaskCreatorSummary = getSummaryDataPoJoByAttr(summaryList, PaymentTaskEnum.CREATOR_ID.getAttr());
                if (Objects.nonNull(paymentTaskCreatorSummary) && Objects.nonNull(paasFormDataEntityExt)) {
                    paymentTaskCreatorSummary.setAttr(PaymentTaskEnum.CREATOR_ID.getAttr());
                    paymentTaskCreatorSummary.setSaasAttr(PaymentTaskEnum.CREATOR_ID.getSaasAttr());
                    paymentTaskCreatorSummary.setAttrName(PaymentTaskEnum.CREATOR_ID.getAttrName());
                    paymentTaskCreatorSummary.setFieldType(PaymentTaskEnum.CREATOR_ID.getFieldType());
                    // 系统生成的访客计划（智能助手）
                    String creatorName;
                    if(Objects.equals(PaasConstant.SYS_USER_ID, paasFormDataEntityExt.getCreatorId())) {
                        creatorName = I18nMessageUtil.getMessage(PaasConstant.SYS_GENERATED);
                    } else {
                        UserEntity userEntity = userModel.getByKey(paasFormDataEntityExt.getCreatorId(), corpid);
                        creatorName = Objects.isNull(userEntity) ? "" : Objects.toString(userEntity.getName(), "");
                    }
                    paymentTaskCreatorSummary.setValue(Collections.singletonList(creatorName));
                }
                break;
            default:
                break;
        }
        return childProductESList;
    }

    /**
     * Description: 公海池特殊处理 负责人->前负责人
     * @param corpid
     * @param summaryList
     * @param dataId
     * @throws XbbException
     * @author 刘阳
     * @date 2019/7/8 3:23 PM
     * @since v1.0
     */
    @Override
    public void handelPublic(String corpid, List<SummaryDataPoJo> summaryList, Long dataId, Integer businessType) throws XbbException {
        List<Long> dataIdList = new ArrayList<>();
        dataIdList.add(dataId);
        Map<Long,String> mainUserMap = userTeamService.getMainUserMap(dataIdList,corpid,businessType,true);
        for(SummaryDataPoJo poJo : summaryList) {
            if (Objects.equals(poJo.getAttr(), FieldTypeEnum.OWNERID.getAlias())) {
                List<Object> userList = new ArrayList<>();
                userList.add(mainUserMap.getOrDefault(dataId,""));
                poJo.setValue(userList);
                poJo.setAttrName(FieldTypeEnum.PRE_OWNER_ID.getDescription());
            }
        }
    }

    /**
     * Description: 访客计划延期原因，延期备注
     * @param corpid
     * @param data
     * @param summaryList
     * @param paasFormDataEntityExt
     * @throws XbbException
     * @author 刘阳
     * @date 2019/7/18 9:19 PM
     * @since v1.0
     */
    @Override
    public void handelCommunicatePlan(String corpid, JSONObject data, List<SummaryDataPoJo> summaryList, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException{
        if (data.containsKey(CommunicatePlanEnum.STATUS.getAttr()) && Objects.equals(data.get(CommunicatePlanEnum.STATUS.getAttr()), CommunicatePlanStatusEnum.DELAY.getCode())) {
            if (data.containsKey(CommunicatePlanEnum.DELAY_CAUSE.getAttr())) {
                SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                String text = "";
                String delayCause = data.getString(CommunicatePlanEnum.DELAY_CAUSE.getAttr());
                List<ItemPoJo> dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.DELAY_CAUSE, corpid, paasFormDataEntityExt.getFormId());
                for (ItemPoJo poJo : dictionaryItemList) {
                    if (Objects.equals(poJo.getValue().toString(), delayCause)) {
                        text = poJo.getText();
                    }
                }
                if (delayCause != null) {
                    summaryDataPoJo.setAttr(CommunicatePlanEnum.DELAY_CAUSE.getAttr());
                    summaryDataPoJo.setSaasAttr(CommunicatePlanEnum.DELAY_CAUSE.getSaasAttr());
                    summaryDataPoJo.setAttrName(CommunicatePlanEnum.DELAY_CAUSE.getAttrName());
                    summaryDataPoJo.setFieldType(CommunicatePlanEnum.DELAY_CAUSE.getFieldType());
                    summaryDataPoJo.setValue(Collections.singletonList(text));
                    summaryList.add(summaryDataPoJo);
                }
            }
            if (data.containsKey(CommunicatePlanEnum.DELAY_MEMO.getAttr())) {
                SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                String delayMemo = data.getString(CommunicatePlanEnum.DELAY_MEMO.getAttr());
                if (delayMemo != null) {
                    summaryDataPoJo.setAttr(CommunicatePlanEnum.DELAY_MEMO.getAttr());
                    summaryDataPoJo.setSaasAttr(CommunicatePlanEnum.DELAY_MEMO.getSaasAttr());
                    summaryDataPoJo.setAttrName(CommunicatePlanEnum.DELAY_MEMO.getAttrName());
                    summaryDataPoJo.setFieldType(CommunicatePlanEnum.DELAY_MEMO.getFieldType());
                    summaryDataPoJo.setValue(Collections.singletonList(delayMemo));
                    summaryList.add(summaryDataPoJo);
                }
            }
        }
    }

    /**
     * Description: 处理访客计划延期标签问题
     * @param labelsList
     * @param data
     * @throws XbbException
     * @author 刘阳
     * @date 2019/7/15 6:48 PM
     * @since v1.0
     */
    @Override
    public void handleCommunicatePlan(List<SummaryDataPoJo> labelsList, JSONObject data) throws XbbException {
        if (data.containsKey(CommunicatePlanEnum.STATUS.getAttr())) {
            if (Objects.equals(data.get(CommunicatePlanEnum.STATUS.getAttr()), CommunicatePlanStatusEnum.DELAY.getCode())){
                SummaryDataPoJo poJo = new SummaryDataPoJo();
                poJo.setAttr(CommunicatePlanEnum.STATUS.getAttr());
                poJo.setSaasAttr(CommunicatePlanEnum.STATUS.getSaasAttr());
                poJo.setValue(Collections.singletonList(CommunicatePlanStatusEnum.DELAY.getAlias()));
                poJo.setAttrName(CommunicatePlanEnum.STATUS.getAttrName());
                poJo.setFieldType(CommunicatePlanEnum.STATUS.getFieldType());
                labelsList.add(poJo);
            } else if ((Objects.equals(data.get(CommunicatePlanEnum.STATUS.getAttr()), CommunicatePlanStatusEnum.NO_FOLLOW.getCode()))) {
                SummaryDataPoJo poJo = new SummaryDataPoJo();
                poJo.setAttr(CommunicatePlanEnum.STATUS.getAttr());
                poJo.setSaasAttr(CommunicatePlanEnum.STATUS.getSaasAttr());
                poJo.setValue(Collections.singletonList(CommunicatePlanStatusEnum.NO_FOLLOW.getAlias()));
                poJo.setAttrName(CommunicatePlanEnum.STATUS.getAttrName());
                poJo.setFieldType(CommunicatePlanEnum.STATUS.getFieldType());
                labelsList.add(poJo);
            } else if ((Objects.equals(data.get(CommunicatePlanEnum.STATUS.getAttr()), CommunicatePlanStatusEnum.FINISH.getCode()))) {
                SummaryDataPoJo poJo = new SummaryDataPoJo();
                poJo.setAttr(CommunicatePlanEnum.STATUS.getAttr());
                poJo.setSaasAttr(CommunicatePlanEnum.STATUS.getSaasAttr());
                poJo.setValue(Collections.singletonList(CommunicatePlanStatusEnum.FINISH.getAlias()));
                poJo.setAttrName(CommunicatePlanEnum.STATUS.getAttrName());
                poJo.setFieldType(CommunicatePlanEnum.STATUS.getFieldType());
                labelsList.add(poJo);
            } else if ((Objects.equals(data.get(CommunicatePlanEnum.STATUS.getAttr()), CommunicatePlanStatusEnum.CANCEL.getCode()))) {
                SummaryDataPoJo poJo = new SummaryDataPoJo();
                poJo.setAttr(CommunicatePlanEnum.STATUS.getAttr());
                poJo.setSaasAttr(CommunicatePlanEnum.STATUS.getSaasAttr());
                poJo.setValue(Collections.singletonList(CommunicatePlanStatusEnum.CANCEL.getAlias()));
                poJo.setAttrName(CommunicatePlanEnum.STATUS.getAttrName());
                poJo.setFieldType(CommunicatePlanEnum.STATUS.getFieldType());
                labelsList.add(poJo);
            }
        }
    }

    /**
     * 获取移动端详情基本信息中的底部信息
     *
     * @param corpid       公司id
     * @param userId       用户id
     * @param businessType 业务类型
     * @param dataId       数据id
     * @param data         表单数据
     * @return JSONArray
     * @author GuoJun.HU
     * @date 2019/3/13 18:50
     * @since V1.0
     */
    @Override
    public JSONArray getBottomBlockInfo(String corpid, String userId, Integer businessType,
                                        Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt entityExt, FormDataGetDTO formDataGetDTO) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<UserEntity> userEntityList;
        List<CustomerUserPojo> userPojoList = new ArrayList<>();
        List<String> userIdIn = new ArrayList<>();
        userIdIn.add("-1");

        Integer editAfterFinish = 0;
        JSONArray bottomBlockInfo = new JSONArray();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                Integer isPublic = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
                if (!Objects.equals(isPublic, BasicConstant.ONE)) {
                    param.put("corpid", corpid);
                    param.put("del", 0);
                    param.put("customerId", dataId);
                    List<CustomerUserEntity> customerUserEntityList = customerUserModel.findEntitys(param);
                    customerUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                    userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                    userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                    customerUserEntityList.forEach(item -> {
                        UserEntity userEntity = userMap.get(item.getUserId());
                        if (userEntity != null) {
                            CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                            customerUserPojo.setUserId(userEntity.getUserId());
                            customerUserPojo.setName(userEntity.getName());
                            customerUserPojo.setAvatar(userEntity.getAvatar());
                            customerUserPojo.setIsMain(item.getIsMain());
                            userPojoList.add(customerUserPojo);
                        }
                    });
                    bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                }
                editAfterFinish = isEditable(corpid, explainMap, entityExt, CustomerManagementEnum.TYPE.getAttr(), formDataGetDTO);
                bottomBlockInfo.add(getMobileDetailStatusBlockPojo(corpid, data, DictionaryEnum.CUSTOMER_STATUS, CustomerManagementEnum.TYPE.getAttr(), editAfterFinish));
                break;
            case SALES_OPPORTUNITY:
                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("opportunityId", dataId);
                List<OpportunityUserEntity> opportunityUserList = opportunityUserModel.findEntitys(param);
                opportunityUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                opportunityUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), 0L);
                if(Objects.nonNull(customerId)){
                    PaasFormDataEntityExt paasFormDataEntity = formDataHelp.getFormData(corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), customerId);
                    if(Objects.nonNull(paasFormDataEntity)){
                        Long formId = paasFormDataEntity.getFormId();
                        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, SalesOpportunityEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                        bottomBlockInfo.add(new MobileDetailDirectBlockPojo(customerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), customerName,formId));
                    }
                }
                break;
            case PURCHASE:
                Long supplier = FastJsonHelper.getLongOrDefaultFromFormData(data, PurchaseEnum.SUPPLIER_ID.getAttr(), 0L);
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(data, PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(supplier, XbbRefTypeEnum.SUPPLIER.getCode(), supplierName));

                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("purchaseId", dataId);
                List<PurchaseUserEntity> purchaseUserList = purchaseUserModel.findEntitys(param);
                purchaseUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                purchaseUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                String purchaseStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, PurchaseEnum.STATUS.getAttr(), "");
                editAfterFinish = isEditable(corpid, explainMap, entityExt, PurchaseEnum.STATUS.getAttr(), formDataGetDTO);
                List<ItemPoJo> itemPoJoList = new ArrayList<>();
                FieldAttrEntity statusField = explainMap.get(PurchaseEnum.STATUS.getAttr());
                if (Objects.nonNull(statusField)) {
                    itemPoJoList = statusField.getItems();
                    itemPoJoList.forEach(item -> {
                        if (Objects.equals(item.getValue(), purchaseStatus)) {
                            item.setChecked(true);
                        } else {
                            item.setChecked(false);
                        }
                    });
                }
                bottomBlockInfo.add(new MobileDetailStatusBlockPojo(itemPoJoList, editAfterFinish));
                break;
            case SUPPLIER:
                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("supplierId", dataId);
                List<SupplierUserEntity> supplierUserList = supplierUserModel.findEntitys(param);
                supplierUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                supplierUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery("data." + PurchaseEnum.SUPPLIER_ID.getAttr(), dataId));
                boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.PASS.getType(), FlowStatusEnum.NOT_NEED_APPROVAL.getType())));
                ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, null);

                List<ConditionsEntityExt> purchaseCondictions = new ArrayList<>();
                ConditionsEntityExt purchaseCondiction = new ConditionsEntityExt(PurchaseEnum.SUPPLIER_ID.getAttr(), "", PurchaseEnum.SUPPLIER_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                purchaseCondictions.add(purchaseCondiction);
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(XbbRefTypeEnum.PURCHASE.getCode(),String.format(I18nMessageUtil.getMessage(StringConstant.PURCHASE_COUNT), StringUtil.toInt(elasticAggsPojo.getTotal(), BasicConstant.ZERO)), purchaseCondictions, BasicConstant.ONE));
                break;
            case WAREHOUSE:
                param.put("corpid", corpid);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("warehouseId", dataId);
                param.put("warehouseChecked", 1);
                int productCount = productWarehouseModel.getEntitysCount(param);
                bottomBlockInfo.add(new MobileDetailTextBlockPojo(String.format(I18nMessageUtil.getMessage(StringConstant.WAREHOUSE_PRODUCT_KIND), productCount)));
                //获取仓库的负责人团队
                param.put("dataId",dataId);
                param.put("type",BasicConstant.ZERO);
                List<WarehouseUserEntity> warehouseUserEntityList = warehouseUserModel.findEntitys(param);
                warehouseUserEntityList.forEach(item -> userIdIn.add(item.getRelationId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                userEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (Objects.nonNull(userEntity)) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                break;
            case CONTACT:
                param.put(StringConstant.CORPID, corpid);
                param.put(StringConstant.DEL, DelEnum.NORMAL);
                param.put(StringConstant.DATA_ID, dataId);
                List<ContactUserEntity> contactUserEntityList = contactUserModel.findEntitys(param);
                contactUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                contactUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                Long contactCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, ContactEnum.CUSTOMER_NAME.getAttr(), 0L);
                String contactCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(contactCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), contactCustomerName));
                break;
            case SUPPLIER_CONTACT:
                param.put(StringConstant.CORPID, corpid);
                param.put(StringConstant.DEL, DelEnum.NORMAL);
                param.put("contactId", dataId);
                List<SupplierContactUserEntity> supplierContactUserEntityList = supplierContactUserModel.findEntitys(param);
                supplierContactUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                supplierContactUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(data, SupplierContactEnum.SUPPLIER_ID.getAttr(), 0L);
                String contactSupplierName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(supplierId, XbbRefTypeEnum.SUPPLIER.getCode(), contactSupplierName));
                break;
            case PRODUCTIONORDER:
                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("productionOrderId", dataId);
                List<ProductionOrderUserEntity> productionOrderUserList = productionOrderUserModel.findEntitys(param);
                productionOrderUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                productionOrderUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                String productionStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, ProductionOrderEnum.STATUS.getAttr(), "");
                List<JSONObject> productionObjectList = ProductionOrderStatusEnum.getItemPoJoList(productionStatus);
                List<ItemPoJo> productionItemPoJoList = new ArrayList<>();
//                editAfterFinish = isEditable(explainMap, entityExt, ProductionOrderEnum.STATUS.getAttr(), formDataGetDTO.getLoginUser());
                editAfterFinish = 1;
                productionObjectList.forEach(item -> {
                    ItemPoJo itemPoJo = JSON.toJavaObject(item, ItemPoJo.class);
                    productionItemPoJoList.add(itemPoJo);
                });
                bottomBlockInfo.add(new MobileDetailStatusBlockPojo(productionItemPoJoList, editAfterFinish));
                break;
            case BOMBILL:
                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("bomId", dataId);
                List<BomUserEntity> bomUserList = bomUserModel.findEntitys(param);
                bomUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                bomUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                String bomStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, BomBillEnum.STATUS.getAttr(), "");
                List<JSONObject> bomObjectList = BomStatusEnum.getItemPoJoList(bomStatus);
                List<ItemPoJo> bomItemPoJoList = new ArrayList<>();
                editAfterFinish = isEditable(corpid, explainMap, entityExt, BomBillEnum.STATUS.getAttr(), formDataGetDTO);
                bomObjectList.forEach(item -> {
                    ItemPoJo itemPoJo = JSON.toJavaObject(item, ItemPoJo.class);
                    bomItemPoJoList.add(itemPoJo);
                });
                bottomBlockInfo.add(new MobileDetailStatusBlockPojo(bomItemPoJoList, editAfterFinish));
                break;
            case CONTRACT:
                Long contractCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, ContractEnum.LINK_CUSTOMER.getAttr(), 0L);
                String contractCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, ContractEnum.LINK_CUSTOMER_HIDE.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(contractCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), contractCustomerName));

                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("contractId", dataId);
                List<ContractUserEntity> contractUserList = contractUserModel.findEntitys(param);
                contractUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                contractUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                editAfterFinish = isEditable(corpid, explainMap, entityExt, ContractEnum.STATUS.getAttr(), formDataGetDTO);
                bottomBlockInfo.add(getMobileDetailStatusBlockPojo(corpid, data, DictionaryEnum.CONTRACT_STATUS, ContractEnum.STATUS.getAttr(), editAfterFinish));
                break;
            case INVOICE:
                JSONArray applyUserArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, InvoiceEnum.APPLY_USER.getAttr(), new JSONArray());
                if (!applyUserArr.isEmpty()) {
                    JSONObject applyUser = applyUserArr.getJSONObject(0);
                    if (applyUser != null && !applyUser.isEmpty()) {
                        //申请人只有一个
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(applyUser.getString("userId"));
                        customerUserPojo.setName(applyUser.getString(StringConstant.SAAS_LINK_BUSINESS_NAME));
                        customerUserPojo.setAvatar(applyUser.getString("avatar"));
                        userPojoList.add(customerUserPojo);
                    }
                }

                bottomBlockInfo.add(new MobileDetailExecutorBlockPojo(userPojoList));
                Long invoiceCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, InvoiceEnum.CUSTOMER_NAME.getAttr(), 0L);
                String invoiceCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, InvoiceEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(invoiceCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), invoiceCustomerName));
                break;
            case PURCHASE_INVOICE:
                JSONArray purchaseInvoiceApplyUserArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PurchaseInvoiceEnum.APPLY_USER.getAttr(), new JSONArray());
                if (!purchaseInvoiceApplyUserArr.isEmpty()) {
                    JSONObject applyUser = purchaseInvoiceApplyUserArr.getJSONObject(0);
                    if (applyUser != null && !applyUser.isEmpty()) {
                        //申请人只有一个
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(applyUser.getString("userId"));
                        customerUserPojo.setName(applyUser.getString(StringConstant.SAAS_LINK_BUSINESS_NAME));
                        customerUserPojo.setAvatar(applyUser.getString("avatar"));
                        userPojoList.add(customerUserPojo);
                    }
                }

                bottomBlockInfo.add(new MobileDetailExecutorBlockPojo(userPojoList));
                Long purchaseInvoiceCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data,PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(), 0L);
                String purchaseInvoiceCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data,PurchaseInvoiceEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(purchaseInvoiceCustomerId, XbbRefTypeEnum.SUPPLIER.getCode(), purchaseInvoiceCustomerName));
                break;
            case PAYMENT:
                Long paymentCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentEnum.CUSTOMER.getAttr(), 0L);
                String paymentCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentEnum.CUSTOMER_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(paymentCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), paymentCustomerName));


                param.put(StringConstant.CORPID, corpid);
                param.put(StringConstant.DEL, DelEnum.NORMAL);
                param.put(StringConstant.DATA_ID, dataId);
                List<PaymentUserEntity> paymentUserEntityList = paymentUserModel.findEntitys(param);
                paymentUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                paymentUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                String paymentStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UNKNOWN.getCode());
                PaymentStatusEnum paymentStatusEnum = PaymentStatusEnum.getByCode(paymentStatus);
                bottomBlockInfo.add(new MobileDetailTextBlockPojo(paymentStatusEnum.getAlias()));
                break;
            case PAY_PLAN:
                Long payPlanSupplierId = FastJsonHelper.getLongOrDefaultFromFormData(data, PayPlanEnum.LINK_SUPPLIER.getAttr(), 0L);
                String payPlanSupplierName = FastJsonHelper.getStringOrDefaultFromFormData(data, PayPlanEnum.LINK_SUPPLIER_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(payPlanSupplierId, XbbRefTypeEnum.SUPPLIER.getCode(), payPlanSupplierName));

                param.put(StringConstant.CORPID, corpid);
                param.put(StringConstant.DEL, DelEnum.NORMAL);
                param.put(StringConstant.DATA_ID, dataId);
                List<PayPlanUserEntity> payPlanUserEntityList = payPlanUserModel.findEntitys(param);
                payPlanUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                payPlanUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                String payPlanStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, PayPlanEnum.STATUS.getAttr(), PayPlanEnum.UN_AMOUNT.getAttr());
                PayPlanStatusEnum payPlanStatusEnum = PayPlanStatusEnum.getByCode(payPlanStatus);
                bottomBlockInfo.add(new MobileDetailTextBlockPojo(payPlanStatusEnum.getAlias()));
                break;
            case RETURNED_PURCHASE:
                setBlockPojo(corpid, entityExt.getOwnerId(), bottomBlockInfo);
                Long returnSupplierId = FastJsonHelper.getLongOrDefaultFromFormData(data, ReturnedPurchaseEnum.SUPPLIER_ID.getAttr(), 0L);
                PaasFormDataEntityExt paasFormDataEntityExt = saasGetHelp.getFormData(returnSupplierId, corpid, XbbRefTypeEnum.SUPPLIER.getCode());
                if (paasFormDataEntityExt != null) {
                    JSONObject supplierFormData = paasFormDataEntityExt.getData();
                    String returnSupplierName = FastJsonHelper.getStringOrDefaultFromFormData(supplierFormData, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                    bottomBlockInfo.add(new MobileDetailDirectBlockPojo(returnSupplierId, XbbRefTypeEnum.SUPPLIER.getCode(), returnSupplierName));
                }
                String outStockId = FastJsonHelper.getStringOrDefaultFromFormData(data, ReturnedPurchaseEnum.OUTSTOCK_ID.getAttr(), "");
                String outStockStatus = StringUtil.isEmpty(outStockId) ? I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK) : I18nMessageUtil.getMessage(I18nStringConstant.OUT_STOCK);
                bottomBlockInfo.add(new MobileDetailTextBlockPojo(outStockStatus));
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                setBlockPojo(corpid, entityExt.getOwnerId(), bottomBlockInfo);
                Integer inStockType = getIntegerOrDefaultFromFormData(data, InstockEnum.TYPE.getAttr(), 0);
                InstockTypeEnum instockTypeEnum = InstockTypeEnum.getByCode(inStockType);
                if (Objects.equals(instockTypeEnum, InstockTypeEnum.PURCHASE_INSTOCK)) {
                    // 采购入库显示采购合同关联的供应商
                    Long refId = FastJsonHelper.getLongOrDefaultFromFormData(data, InstockEnum.REF_ID.getAttr(), 0L);
                    PaasFormDataEntityExt paasFormPurchaseDataEntityExt = saasGetHelp.getFormData(refId, corpid, XbbRefTypeEnum.PURCHASE.getCode());
                    JSONObject purchaseFormData = paasFormPurchaseDataEntityExt.getData();
                    HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                    BeanUtil.copyProperties(formDataGetDTO, handlerExplainDTO);
                    Boolean invisible = ExplainUtil.invisibleOfScope(explainMap.get(PurchaseEnum.SUPPLIER_ID.getAttr()), handlerExplainDTO);
                    if (invisible) {
                        Long purchaseSupplierId = FastJsonHelper.getLongOrDefaultFromFormData(purchaseFormData, PurchaseEnum.SUPPLIER_ID.getAttr(), 0L);
                        String purchaseSupplierName = FastJsonHelper.getStringOrDefaultFromFormData(purchaseFormData, PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), "");
                        bottomBlockInfo.add(new MobileDetailDirectBlockPojo(purchaseSupplierId, XbbRefTypeEnum.SUPPLIER.getCode(), purchaseSupplierName));
                    }
                }
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case ORDER_OUTSTOCK:
                setBlockPojo(corpid, entityExt.getOwnerId(), bottomBlockInfo);
                break;
            case INVENTORY:
                setBlockPojo(corpid, entityExt.getOwnerId(), bottomBlockInfo);
                break;
            case TRANSFER:
                setBlockPojo(corpid, entityExt.getOwnerId(), bottomBlockInfo);
                break;
            case ASSEMBLE:
                setBlockPojo(corpid, entityExt.getOwnerId(), bottomBlockInfo);
                break;
            case COMMUNICATE_PLAN:
                Long communicatePlanCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), 0L);
                String communicatePlanCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicatePlanEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(communicatePlanCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), communicatePlanCustomerName));

                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("planId", dataId);
                List<CommunicatePlanUserEntity> planUserList = communicatePlanUserModel.findEntitys(param);
                planUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));

                // 对拥有相同 UserId 的CommunicatePlanUserEntity队列进行排重
                Set<String> userIdSet = new HashSet<>();
                Iterator<CommunicatePlanUserEntity> userEntityIterator = planUserList.iterator();
                while (userEntityIterator.hasNext()) {
                    CommunicatePlanUserEntity userEntity = userEntityIterator.next();
                    if (userIdSet.contains(userEntity.getUserId())) {
                        userEntityIterator.remove();
                    } else {
                        userIdSet.add(userEntity.getUserId());
                    }
                }
                planUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailExecutorBlockPojo(userPojoList));
                break;
            case REFUND:
                param.put("corpid", corpid);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("refundId", dataId);
                List<RefundUserEntity> refundUserEntityList = refundUserModel.findEntitys(param);
                refundUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                refundUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo refundUserPojo = new CustomerUserPojo();
                        refundUserPojo.setUserId(userEntity.getUserId());
                        refundUserPojo.setName(userEntity.getName());
                        refundUserPojo.setAvatar(userEntity.getAvatar());
                        refundUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(refundUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                Long refundId = FastJsonHelper.getLongOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID.getAttr(), 0L);
                String refundCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(refundId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), refundCustomerName));
                break;
            case RETURN:
                param.put("corpid", corpid);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("refundId", dataId);
                refundUserEntityList = refundUserModel.findEntitys(param);
                refundUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                refundUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo refundUserPojo = new CustomerUserPojo();
                        refundUserPojo.setUserId(userEntity.getUserId());
                        refundUserPojo.setName(userEntity.getName());
                        refundUserPojo.setAvatar(userEntity.getAvatar());
                        refundUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(refundUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                refundId = FastJsonHelper.getLongOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID.getAttr(), 0L);
                refundCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(refundId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), refundCustomerName));
                break;
            case WORKORDER:
                param.put("corpid",corpid);
                param.put("del",0);
                param.put("workOrderId",dataId);
                List<WorkOrderFlowUserEntity> workOrderFlowUserEntityList = workOrderFlowUserModel.findEntitys(param);
                workOrderFlowUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                workOrderFlowUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo workOrderUserPojo = new CustomerUserPojo();
                        workOrderUserPojo.setUserId(userEntity.getUserId());
                        workOrderUserPojo.setName(userEntity.getName());
                        workOrderUserPojo.setAvatar(userEntity.getAvatar());
                        workOrderUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(workOrderUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                break;
            case QUOTATION:
                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("quotationId", dataId);
                List<QuotationUserEntity> quotationUserEntities = quotationUserModel.findEntitys(param);
                quotationUserEntities.forEach(item-> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                quotationUserEntities.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo quotationUserPojo = new CustomerUserPojo();
                        quotationUserPojo.setUserId(userEntity.getUserId());
                        quotationUserPojo.setName(userEntity.getName());
                        quotationUserPojo.setAvatar(userEntity.getAvatar());
                        quotationUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(quotationUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                FieldAttrEntity attrEntity = explainMap.get(QuotationEnum.STATUS.getAttr());
                if (attrEntity != null) {
                    List<ItemPoJo> items = attrEntity.getItems();
                    String quotationStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, QuotationEnum.STATUS.getAttr(), "");
                    items.forEach(itemPoJo -> {
                        if (Objects.equals(itemPoJo.getValue(), quotationStatus)) {
                            itemPoJo.setChecked(true);
                        } else {
                            itemPoJo.setChecked(false);
                        }
                    });
                    MobileDetailStatusBlockPojo statusBlockPojo = new MobileDetailStatusBlockPojo();
                    editAfterFinish = isEditable(corpid, explainMap, entityExt, QuotationEnum.STATUS.getAttr(), formDataGetDTO);
                    statusBlockPojo.setEditable(editAfterFinish);
                    statusBlockPojo.setOptions(items);
                    bottomBlockInfo.add(statusBlockPojo);
                }
                break;
            case PAYMENT_SHEET:
                Long sheetCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentSheetEnum.CUSTOMER_ID.getAttr(), 0L);
                String sheetCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentSheetEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(sheetCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), sheetCustomerName));


                param.put(StringConstant.CORPID, corpid);
                param.put(StringConstant.DEL, DelEnum.NORMAL);
                param.put(StringConstant.DATA_ID, dataId);
                List<PaymentSheetUserEntity> paymentSheetUserEntityList = paymentSheetUserModel.findEntitys(param);
                paymentSheetUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                paymentSheetUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.UNKNOWN.getCode());
                PaymentSheetTypeEnum paymentSheetTypeEnum = PaymentSheetTypeEnum.getByCode(paymentSheetType);
                bottomBlockInfo.add(new MobileDetailTextBlockPojo(paymentSheetTypeEnum.getName()));
                break;
            case PAY_SHEET:
                Long sheetSupplierId = FastJsonHelper.getLongOrDefaultFromFormData(data, PaySheetEnum.LINK_SUPPLIER.getAttr(), 0L);
                String sheetSupplierName = FastJsonHelper.getStringOrDefaultFromFormData(data, PaySheetEnum.SUPPLIER_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(sheetSupplierId, XbbRefTypeEnum.SUPPLIER.getCode(), sheetSupplierName));

                param.put(StringConstant.CORPID, corpid);
                param.put(StringConstant.DEL, DelEnum.NORMAL);
                param.put(StringConstant.DATA_ID, dataId);
                List<PayPlanSheetUserEntity> payPlanSheetUserEntityList = payPlanSheetUserModel.findEntitys(param);
                payPlanSheetUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                payPlanSheetUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));

                String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(data, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.UNKNOWN.getCode());
                PaySheetTypeEnum paySheetTypeEnum = PaySheetTypeEnum.getByCode(paySheetType);
                bottomBlockInfo.add(new MobileDetailTextBlockPojo(paySheetTypeEnum.getName()));
                break;
            case PAYMENT_TASK:
                Long paymentTaskCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentTaskEnum.LINK_CUSTOMER.getAttr(), 0L);
                String paymentTaskCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentTaskEnum.LINK_CUSTOMER_HIDE.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(paymentTaskCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), paymentTaskCustomerName));

                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("planId", dataId);
                List<PaymentTaskUserEntity> paymentTaskUserList = paymentTaskUserModel.findEntitys(param);
                paymentTaskUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));

                // 对拥有相同 UserId 的paymentTaskUserList队列进行排重
                Set<String> paymentTaskUserIdSet = new HashSet<>();
                Iterator<PaymentTaskUserEntity> paymentTaskUserEntityIterator = paymentTaskUserList.iterator();
                while (paymentTaskUserEntityIterator.hasNext()) {
                    PaymentTaskUserEntity userEntity = paymentTaskUserEntityIterator.next();
                    if (paymentTaskUserIdSet.contains(userEntity.getUserId())) {
                        paymentTaskUserEntityIterator.remove();
                    } else {
                        paymentTaskUserIdSet.add(userEntity.getUserId());
                    }
                }
                paymentTaskUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailExecutorBlockPojo(userPojoList));
                break;
            case DISTRIBUTOR_CONTACT:
                Long contactDistributorId = FastJsonHelper.getLongOrDefaultFromFormData(data, DistributorContactEnum.DISTRIBUTOR_NAME.getAttr(), 0L);
                String contactDistributorName = FastJsonHelper.getStringOrDefaultFromFormData(data, DistributorContactEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(contactDistributorId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), contactDistributorName, DistributorMarkEnum.DISTRIBUTOR.getCode()));
                break;
            case ORDER:
                contractCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, OrderEnum.LINK_DISTRIBUTOR.getAttr(), 0L);
                contractCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(data, OrderEnum.LINK_CUSTOMER_HIDE.getAttr(), "");
                bottomBlockInfo.add(new MobileDetailDirectBlockPojo(contractCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), contractCustomerName, DistributorMarkEnum.DISTRIBUTOR.getCode()));

                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("contractId", dataId);
                contractUserList = contractUserModel.findEntitys(param);
                contractUserList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                contractUserList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                // 不展示订货单状态，先注释
                // editAfterFinish = isEditable(corpid, explainMap, entityExt, OrderEnum.STATUS.getAttr(), formDataGetDTO);
                // bottomBlockInfo.add(getMobileDetailStatusBlockPojo(corpid, data, DictionaryEnum.CONTRACT_STATUS, OrderEnum.STATUS.getAttr(), editAfterFinish));
                break;
            case PAAS:
                setBlockPojo(corpid, entityExt.getOwnerId(), bottomBlockInfo);
                break;
            case MARKET_ACTIVITY:
                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("dataId", dataId);
                List<MarketActivityUserEntity> marketActivityUserEntityList = marketActivityUserModel.findEntitys(param);
                marketActivityUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                marketActivityUserEntityList.forEach(item -> {
                    UserEntity userEntity = userMap.get(item.getUserId());
                    if (userEntity != null) {
                        CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                        customerUserPojo.setUserId(userEntity.getUserId());
                        customerUserPojo.setName(userEntity.getName());
                        customerUserPojo.setAvatar(userEntity.getAvatar());
                        customerUserPojo.setIsMain(item.getIsMain());
                        userPojoList.add(customerUserPojo);
                    }
                });
                bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                break;
            case CLUE:
                Integer publicFlag = getIntegerOrDefaultFromFormData(data, ClueEnum.IS_PUBLIC.getAttr(), 0);
                if (!Objects.equals(publicFlag, 1)) {
                    param.put("corpid", corpid);
                    param.put("del", 0);
                    param.put("dataId", dataId);
                    List<ClueUserEntity> clueUserEntityList = clueUserModel.findEntitys(param);
                    clueUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
                    userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
                    userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
                    clueUserEntityList.forEach(item -> {
                        UserEntity userEntity = userMap.get(item.getUserId());
                        if (userEntity != null) {
                            CustomerUserPojo customerUserPojo = new CustomerUserPojo();
                            customerUserPojo.setUserId(userEntity.getUserId());
                            customerUserPojo.setName(userEntity.getName());
                            customerUserPojo.setAvatar(userEntity.getAvatar());
                            customerUserPojo.setIsMain(item.getIsMain());
                            userPojoList.add(customerUserPojo);
                        }
                    });
                    bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
                }
                break;
            default:
                break;
        }

        return bottomBlockInfo;
    }

    @Override
    public JSONArray getPaasBottomBlockInfo(String corpid, String userId, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt paasFormDataEntityExt, FormDataGetDTO formDataGetDTO) throws XbbException {
        JSONArray bottomBlockInfo = new JSONArray();
        FieldAttrEntity ownerIdFieldAttr = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
        FieldAttrEntity coUserIdFieldAttr = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
        if (Objects.isNull(ownerIdFieldAttr) || Objects.isNull(coUserIdFieldAttr)) {
            return bottomBlockInfo;
        }
        Map<String, Object> map = new HashMap<>();
        map.put(StringConstant.CORPID, corpid);
        map.put("dataIdIn", Arrays.asList(dataId));
        map.put(StringConstant.DEL, BasicConstant.ZERO);
        List<PaasUserEntity> paasUserEntities = paasUserModel.findEntitys(map);
        if (CollectionsUtil.isEmpty(paasUserEntities)) {
            return bottomBlockInfo;
        }
        List<String> userIdIn = new ArrayList<>();
        paasUserEntities.forEach(item -> userIdIn.add(item.getUserId()));
        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
        List<CustomerUserPojo> userPojoList = new ArrayList<>();
        for (UserEntity userEntity : userEntityList) {
            CustomerUserPojo customerUserPojo1 = new CustomerUserPojo();
            customerUserPojo1.setUserId(userEntity.getUserId());
            customerUserPojo1.setName(userEntity.getName());
            customerUserPojo1.setAvatar(userEntity.getAvatar());
            customerUserPojo1.setIsMain(userEntity.getIsMain());
            userPojoList.add(customerUserPojo1);
        }
        bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
        return bottomBlockInfo;
    }

    /**
     *  详情页是否允许快速编辑字段
     *
     * @param explainMap 字段解释容器
     * @param paasFormDataEntityExt 数据实体
     * @param attr 字段attr
     * @param formDataGetDTO 操作人
     * @return 详情页是否允许快速编辑
     * @author long.rao
     * @date 2019-11-12 11:00
     */
    private Integer isEditable(String corpid, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt paasFormDataEntityExt, String attr, FormDataGetDTO formDataGetDTO) {
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataGetDTO,handlerExplainDTO);
        return processFieldHelp.isEditable(corpid, explainMap, paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getFormId(), paasFormDataEntityExt.getFlowStatus(), attr, handlerExplainDTO);
    }

    @Override
    public List<MobileDetailMoneyItemPojo> getMobileDetailMoneyInfo(Integer distributorMark, String corpid, String userId, Integer businessType,
                                                                    Integer subBusinessType, Long dataId, JSONObject data,
                                                                    Map<String, FieldAttrEntity> explainMap, UserVO loginUser) throws XbbException {
        List<MobileDetailMoneyItemPojo> moneyItemList = new ArrayList<>();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        //千份位小数精度为2
        Integer accuracy = 2;
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                List<PaasFormDataEntityExt> customerCommunicateList = customerCommunicateService.getCustomerCommunicateEsDataListByCustomerId(corpid, dataId);
                Integer customerCommunicateCount = Objects.isNull(customerCommunicateList) ? 0 : customerCommunicateList.size();
                moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.FOLLOW_UP_TIMES), customerCommunicateCount, false));
                FormDataListDTO formDataListDTO = new FormDataListDTO();
                formDataListDTO.setUserId(userId);
                formDataListDTO.setCorpid(corpid);
                formDataListDTO.setExplainMap(explainMap);
                List<PaasFormDataEntityExt> contractList = contractService.getContractEsDataListByCustomerId(corpid, dataId);
                if (Objects.nonNull(contractList)) {
                    AtomicReference<Double> totalAmount = new AtomicReference<>(0D);
                    contractList.forEach(contract -> {
                        JSONObject contractData = contract.getData();
                        Double totalMoney = StringUtil.toDouble(contractData.getString(ContractEnum.AMOUNT.getAttr()), 0D);
                        totalAmount.set(Arith.add(totalAmount.get(), totalMoney));
                    });
                    //订单金额处理为千份位
                    Object orderAmount = AttrDecimalPrecisionHelper.parseThousandth(totalAmount.get(),accuracy);
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.ORDER_AMOUNT),orderAmount, false));
                    List<ConditionsEntityExt> contractCondictions = new ArrayList<>();
                    ConditionsEntityExt contractCondiction = new ConditionsEntityExt(ContractEnum.LINK_CUSTOMER.getAttr(), "", ContractEnum.LINK_CUSTOMER.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                    contractCondictions.add(contractCondiction);
                    contractCondictions.add(EsUtil.packageContions(ContractEnum.IS_RED.getAttr(), Collections.singletonList(0), ConditionEnum.EQUAL, ContractEnum.IS_RED.getFieldType()));
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.CONTRACT_ORDER), contractList.size(), contractCondictions, true, XbbRefTypeEnum.CONTRACT.getCode(), BasicConstant.ONE));
                }
                List<String> codeList = PaymentSheetTypeEnum.getCodeListForCustomerSum();
                List<PaasFormDataEntityExt> paymentSheets = paymentSheetService.getPaymentSheetEsDataListByCustomerId(corpid, dataId, codeList, loginUser);
                if (Objects.nonNull(paymentSheets)) {
                    AtomicReference<Double> paymentAmount = new AtomicReference<>(0D);
                    paymentSheets.forEach(payment -> {
                        JSONObject paymentData = payment.getData();
                        Double totalMoney = StringUtil.toDouble(paymentData.getString(PaymentSheetEnum.AMOUNT.getAttr()), 0D);
                        paymentAmount.set(Arith.add(paymentAmount.get(), totalMoney));
                    });
                    String paymentTotal = attrDecimalPrecisionHelper.formatMoneyPrecision(paymentAmount.get(), accuracy);
                    List<ConditionsEntityExt> paymentCondictions = new ArrayList<>();
                    ConditionsEntityExt paymentCondiction = new ConditionsEntityExt(PaymentSheetEnum.CUSTOMER_ID.getAttr(), "", PaymentSheetEnum.CUSTOMER_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                    paymentCondictions.add(paymentCondiction);
                    moneyItemList.add(new MobileDetailMoneyItemPojo(distributorMark, I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_REFUND), paymentTotal, paymentCondictions,  true, XbbRefTypeEnum.PAYMENT_SHEET.getCode(), BasicConstant.ONE));
                }
                List<PaasFormDataEntityExt> opportunityList = opportunityService.getOpportunityEsDataListByCustomerId(corpid, dataId);
                boolean opportunityMenuFlag = paasMenuService.enableMenu(corpid, XbbRefTypeEnum.SALES_OPPORTUNITY.getAlias());
                if (Objects.nonNull(opportunityList) && opportunityMenuFlag) {
                    List<ConditionsEntityExt> opportunityCondictions = new ArrayList<>();
                    ConditionsEntityExt opportunityCondiction = new ConditionsEntityExt(SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), "", SalesOpportunityEnum.CUSTOMER_NAME.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                    opportunityCondictions.add(opportunityCondiction);
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.SALES_OPPORTUNITIES), opportunityList.size(), opportunityCondictions, true, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), BasicConstant.ONE));
                }
                List<PaasFormDataEntityExt> quotationList = quotationService.getQuotationEsDataListByCustomerId(corpid, dataId);
                boolean quotationMenuFlag = paasMenuService.enableMenu(corpid, XbbRefTypeEnum.QUOTATION.getAlias());
                if (Objects.nonNull(quotationList) && quotationMenuFlag) {
                    List<ConditionsEntityExt> quotationCondictions = new ArrayList<>();
                    ConditionsEntityExt quotationCondiction = new ConditionsEntityExt(QuotationEnum.CUSTOMER_ID.getAttr(), "", QuotationEnum.CUSTOMER_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                    ConditionsEntityExt newVersionCondiction = new ConditionsEntityExt(QuotationEnum.IS_NEW.getAttr(), "", QuotationEnum.IS_NEW.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(BasicConstant.ONE));
                    quotationCondictions.add(quotationCondiction);
                    quotationCondictions.add(newVersionCondiction);
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.QUOTATION), quotationList.size(), quotationCondictions, true, XbbRefTypeEnum.QUOTATION.getCode(), BasicConstant.ONE));
                }
                //应收未收
                List<PaasFormDataEntityExt> paymentList = paymentService.getPaymentEsDataListByCustomerId(corpid,dataId);
                AtomicReference<Double> paymentAmount = new AtomicReference<>(0D);
                paymentList.forEach(payment -> {
                    JSONObject paymentData = payment.getData();
                    Double totalMoney = StringUtil.toDouble(paymentData.getString(PaymentEnum.UN_AMOUNT.getAttr()), 0D);
                    paymentAmount.set(Arith.add(paymentAmount.get(), totalMoney));
                });
                String paymentTotal = attrDecimalPrecisionHelper.formatMoneyPrecision(paymentAmount.get(), accuracy);
                List<ConditionsEntityExt> paymentCondictions = new ArrayList<>();
                ConditionsEntityExt paymentCondiction = new ConditionsEntityExt(PaymentEnum.CUSTOMER.getAttr(), "", PaymentEnum.CUSTOMER.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                paymentCondictions.add(paymentCondiction);
                moneyItemList.add(new MobileDetailMoneyItemPojo(distributorMark, I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_PAYMENT), paymentTotal, paymentCondictions,  true, XbbRefTypeEnum.PAYMENT.getCode(), BasicConstant.ONE));
                break;
            case SALES_OPPORTUNITY:
                String salesUnit = UnitEnum.MONEY.getName();
                FieldAttrEntity fieldAttrEntity = explainMap.get(SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttr());
                if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object estimateAmount = moneyParseThrousandth(fieldAttrEntity,data,SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(fieldAttrEntity.getAttrName() + "/" + salesUnit, estimateAmount, false));
                }
                FieldAttrEntity costFieldAttrEntity = explainMap.get(SalesOpportunityEnum.COST.getAttr());
                if (Objects.nonNull(costFieldAttrEntity) && Objects.equals(costFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object costAmount = moneyParseThrousandth(costFieldAttrEntity,data,SalesOpportunityEnum.COST.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(costFieldAttrEntity.getAttrName() + "/" + salesUnit, costAmount, false));
                }
                FieldAttrEntity grossProfitFieldAttrEntity = explainMap.get(SalesOpportunityEnum.GROSS_PROFIT.getAttr());
                if (Objects.nonNull(grossProfitFieldAttrEntity) && Objects.equals(grossProfitFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object grossProfitAmount = moneyParseThrousandth(grossProfitFieldAttrEntity,data,SalesOpportunityEnum.GROSS_PROFIT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(grossProfitFieldAttrEntity.getAttrName() + "/" + salesUnit,grossProfitAmount, false));
                }
                FieldAttrEntity grossProfitRateFieldAttrEntity = explainMap.get(SalesOpportunityEnum.GROSS_PROFIT_RATE.getAttr());
                if (Objects.nonNull(grossProfitRateFieldAttrEntity) && Objects.equals(grossProfitRateFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    moneyItemList.add(new MobileDetailMoneyItemPojo(grossProfitRateFieldAttrEntity.getAttrName() + "/%", data.getString(SalesOpportunityEnum.GROSS_PROFIT_RATE.getAttr()), false));
                }
                break;
            case PURCHASE:
                FieldAttrEntity moneyFieldAttrEntity = explainMap.get(PurchaseEnum.TOTAL_MONEY.getAttr());
                boolean invisible = false;
                try {
                    PaasFormDataEntityExt paasFormDataEntityExt = purchaseModel.getByKey(dataId, corpid);
                    Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    //协同团队
                    userTeamService.getUserIdMap(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.PURCHASE.getCode(), false, mainUserMap, coUserMap);
                    HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                    handlerExplainDTO.setBusinessType(businessType);
                    handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
                    handlerExplainDTO.setOwnerId(mainUserMap.getOrDefault(dataId, new ArrayList<>()));
                    handlerExplainDTO.setCoUserId(coUserMap.getOrDefault(dataId, new ArrayList<>()));
                    handlerExplainDTO.setExplainList(new ArrayList<>(explainMap.values()));
                    if (Objects.nonNull(moneyFieldAttrEntity)) {
                        invisible = ExplainUtil.isFieldNeedHide(moneyFieldAttrEntity, handlerExplainDTO);
                    }
                } catch (Exception e) {
                    invisible = false;
                }
                FieldAttrEntity unFinishFieldAttrEntity = explainMap.get(PurchaseEnum.UN_FINISH_AMOUNT.getAttr());
                FieldAttrEntity finishFieldAttrEntity = explainMap.get(PurchaseEnum.FINISH_AMOUNT.getAttr());
                FieldAttrEntity badFieldAttrEntity = explainMap.get(PurchaseEnum.BAD_AMOUNT.getAttr());
                String purchaseUnitStr = FastJsonHelper.getStringOrDefaultFromFormData(data, I18nMessageUtil.getMessage(I18nStringConstant.ELEMENT), UnitEnum.MONEY.getName());
                Double totalMoney;
                if (Objects.nonNull(moneyFieldAttrEntity) && Objects.equals(moneyFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    String totalMoneyStr = moneyFieldAttrEntity.getAttrName() + "/" + purchaseUnitStr;
                    Object totalMoneyObject = moneyParseThrousandth(moneyFieldAttrEntity,data,PurchaseEnum.TOTAL_MONEY.getAttr());
                    if (invisible) {
                        totalMoneyObject = StringConstant.INVISIBLE_VALUE;
                    }
                    moneyItemList.add(new MobileDetailMoneyItemPojo(totalMoneyStr, totalMoneyObject, false));
                }
                if (Objects.nonNull(unFinishFieldAttrEntity) && Objects.equals(unFinishFieldAttrEntity.getVisible(),BasicConstant.ONE)) {
                    String finishMoneyStr = unFinishFieldAttrEntity.getAttrName() + "/" + purchaseUnitStr;
                    Object finishMoneyObject = moneyParseThrousandth(unFinishFieldAttrEntity,data,PurchaseEnum.UN_FINISH_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(finishMoneyStr, finishMoneyObject, false));
                }
                if (Objects.nonNull(finishFieldAttrEntity) && Objects.equals(finishFieldAttrEntity.getVisible(),BasicConstant.ONE)) {
                    String unFinishMoneyStr = finishFieldAttrEntity.getAttrName() + "/" + purchaseUnitStr;
                    Object unFinishMoneyObject = moneyParseThrousandth(finishFieldAttrEntity,data,PurchaseEnum.FINISH_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(unFinishMoneyStr, unFinishMoneyObject, false));
                }
                if (Objects.nonNull(badFieldAttrEntity) && Objects.equals(badFieldAttrEntity.getVisible(),BasicConstant.ONE)) {
                    String badMoneyStr = badFieldAttrEntity.getAttrName() + "/" + purchaseUnitStr;
                    Object badMoneyObject = moneyParseThrousandth(badFieldAttrEntity,data,PurchaseEnum.BAD_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(badMoneyStr, badMoneyObject, false));
                }
                break;
            case PAYMENT:
                String paymentUnit = FastJsonHelper.getStringOrDefaultFromFormData(data,  I18nMessageUtil.getMessage(CommonConstant.YUAN), UnitEnum.MONEY.getName());
                FieldAttrEntity paymentRealAmountAttr = explainMap.get(PaymentEnum.REAL_AMOUNT.getAttr());
                Object realAmount = 0D;
                if (paymentRealAmountAttr !=null) {
                    realAmount = moneyParseThrousandth(paymentRealAmountAttr, data, PaymentEnum.REAL_AMOUNT.getAttr());
                }
                FieldAttrEntity paymentUnAmountAttr = explainMap.get(PaymentEnum.UN_AMOUNT.getAttr());
                Object unAmount = 0D;
                if (paymentUnAmountAttr != null) {
                    unAmount = moneyParseThrousandth(paymentUnAmountAttr, data, PaymentEnum.UN_AMOUNT.getAttr());
                }
                Double redTotalAmount = 0D;
                Integer isReceivableRed = FastJsonHelper.getIntegerOrDefaultFromFormData(data, PaymentEnum.RECEIVABLE_IS_RED.getAttr(), 0);
                Integer hasReceivableRed = FastJsonHelper.getIntegerOrDefaultFromFormData(data, PaymentEnum.RECEIVABLE_HAS_RED.getAttr(), 0);
                if (Objects.equals(hasReceivableRed, 1)){
                    redTotalAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data,PaymentEnum.RED_AMOUNT.getAttr(),0D);
                }
                //Integer redPayment = saasUpdateHelp.getIntegerOrDefaultFromFormData(data, PaymentEnum.IS_RED.getAttr(), 0);
                if (Objects.equals(isReceivableRed, 1)) {
                    //moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_PAID_OTHER) + paymentUnit, realAmount, false));
                    return null;
                }
                if (paymentUnAmountAttr != null) {
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.UNPAID_AMOUNT_OTHER) + paymentUnit, unAmount, false));
                }
                if (paymentRealAmountAttr != null) {
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_PAID_OTHER) + paymentUnit, realAmount, false));
                }
                //List<PaasFormDataEntityExt> paymentSheetList = paymentSheetService.getPaymentSheetEsDataListByPaymentId(corpid, dataId);

                Double badTotalAmount = paymentSheetService.sumAmountBySheet(corpid, dataId, PaymentSheetTypeEnum.getBadCodeList());

                Object badAmountThousandth = AttrDecimalPrecisionHelper.parseThousandth(badTotalAmount,accuracy);
                Object redAmountThousandth = AttrDecimalPrecisionHelper.parseThousandth(redTotalAmount,accuracy);
                moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_OF_BAD_DEBTS) + paymentUnit, badAmountThousandth, false));
                moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_OF_RED_RUSH) + paymentUnit, redAmountThousandth, false));
                break;
            case PAY_PLAN:
                FieldAttrEntity realAmountFieldEntity = explainMap.get(PayPlanEnum.REAL_AMOUNT.getAttr());
                FieldAttrEntity unAmountFieldEntity = explainMap.get(PayPlanEnum.UN_AMOUNT.getAttr());
                Long purchaseId = FastJsonHelper.getLongOrDefaultFromFormData(data, PayPlanEnum.LINK_PURCHASE.getAttr(), 0L);
                PurchaseEntityExt purchaseEntityExt = purchaseModel.getByKey(purchaseId, corpid);
                String purchaseUnit = FastJsonHelper.getStringOrDefaultFromFormData(purchaseEntityExt.getData(),  I18nMessageUtil.getMessage(CommonConstant.YUAN), UnitEnum.MONEY.getName());
                if (unAmountFieldEntity != null && Objects.equals(unAmountFieldEntity.getVisible(), BasicConstant.ONE)) {
                    Object payPlanUnAmount = moneyParseThrousandth(unAmountFieldEntity,data,PayPlanEnum.UN_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.UNPAID_AMOUNT) + purchaseUnit, payPlanUnAmount, false));
                }
                if (realAmountFieldEntity != null && Objects.equals(realAmountFieldEntity.getVisible(), BasicConstant.ONE)) {
                    Object payPlanRealAmount = moneyParseThrousandth(realAmountFieldEntity, data, PayPlanEnum.REAL_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.PAID_AMOUNT) + purchaseUnit, payPlanRealAmount, false));
                }
                Double planBadTotalAmount = payPlanSheetService.sumAmountBySheet(corpid, dataId, PaySheetTypeEnum.getBadCodeList());
                //关联红冲
                Double planRedTotalAmount = 0D;
                Integer hasPlanSheetRed = getIntegerOrDefaultFromFormData(data, PayPlanEnum.HAS_RED.getAttr(), 0);
                if (Objects.equals(hasPlanSheetRed, 1)){
                    planRedTotalAmount = payPlanSheetService.sumAmountBySheet(corpid, dataId, PaySheetTypeEnum.getRedCodeList());
                }
                Object planBadAmountThousandth = AttrDecimalPrecisionHelper.parseThousandth(planBadTotalAmount,accuracy);
                Object planRedAmountThousandth = AttrDecimalPrecisionHelper.parseThousandth(planRedTotalAmount,accuracy);
                moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_OF_BAD_DEBTS) + purchaseUnit, planBadAmountThousandth, false));
                moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_OF_RED_RUSH) + purchaseUnit, planRedAmountThousandth, false));
                break;
            case WORKREPORT:
                Integer reportDateInt = data.getInteger(WorkReportFieldEnum.REPORT_DATE.getAttr());
                // subBusinessType外层方法直接处理好，从paasForm中取
//                Integer type = saasUpdateHelp.getIntegerOrDefaultFromFormData(data, WorkReportFieldEnum.TYPE.getAttr(), BasicConstant.ZERO);
//                WorkReportTypeEnum byType = WorkReportTypeEnum.getByType(type);
//                if (byType != null) {
//                    // 推送消息跳详情页,subBusinessType新建时存的是2101，所以这里兼容一下
//                    subBusinessType = byType.getBusinessType();
//                }
                WorkReportDetailStatisticsVO statisticsVO = workReportService.getStatistic(subBusinessType,userId,corpid,reportDateInt,data.getString(WorkReportFieldEnum.THIS_STATISTIC.getAttr()));
                List<WorkReportDetailStatisticResultPojo> statisticResultList = statisticsVO.getStatisticResultList();
                for (WorkReportDetailStatisticResultPojo statisticResultPojo : statisticResultList) {
                    moneyItemList.add(new MobileDetailMoneyItemPojo(statisticResultPojo.getName(), statisticResultPojo.getValue(), statisticResultPojo.getThrough(), true));
                }
                break;
            case CONTRACT:
                FieldAttrEntity contractAmountFieldAttrEntity = explainMap.get(ContractEnum.AMOUNT.getAttr());
                String unit = UnitEnum.MONEY.getName();
                if (Objects.nonNull(contractAmountFieldAttrEntity) && Objects.equals(contractAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractAmount = moneyParseThrousandth(contractAmountFieldAttrEntity,data,ContractEnum.AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractAmountFieldAttrEntity.getAttrName() + "/" +unit, contractAmount, false));
                }
                FieldAttrEntity finishAmountFieldAttrEntity = explainMap.get(ContractEnum.FINISH_AMOUNT.getAttr());
                if (Objects.nonNull(finishAmountFieldAttrEntity) && Objects.equals(finishAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object finishAmount = moneyParseThrousandth(finishAmountFieldAttrEntity,data,ContractEnum.FINISH_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_COLLECTED) + unit, finishAmount, false));
                }
                FieldAttrEntity unfinishAmountFieldAttrEntity = explainMap.get(ContractEnum.UN_FINISH_AMOUNT.getAttr());
                if (Objects.nonNull(unfinishAmountFieldAttrEntity) && Objects.equals(unfinishAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object unFinishAmount = moneyParseThrousandth(unfinishAmountFieldAttrEntity,data,ContractEnum.UN_FINISH_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.UNPAID_AMOUNT_OTHER) + unit, unFinishAmount, false));
                }
                FieldAttrEntity badAmountFieldAttrEntity = explainMap.get(ContractEnum.BAD_AMOUNT.getAttr());
                if (Objects.nonNull(badAmountFieldAttrEntity) && Objects.equals(badAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object badAmount = moneyParseThrousandth(badAmountFieldAttrEntity,data,ContractEnum.BAD_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_OF_BAD_DEBTS) + unit, badAmount, false));
                }
                FieldAttrEntity contractCostFieldAttrEntity = explainMap.get(ContractEnum.CONTRACT_COST.getAttr());
                if (Objects.nonNull(contractCostFieldAttrEntity) && Objects.equals(contractCostFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractCost = moneyParseThrousandth(contractCostFieldAttrEntity,data,ContractEnum.CONTRACT_COST.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractCostFieldAttrEntity.getAttrName() + "/" +unit, contractCost, false));
                }
                FieldAttrEntity contractGrossFieldAttrEntity = explainMap.get(ContractEnum.GROSS_PROFIT.getAttr());
                if (Objects.nonNull(contractGrossFieldAttrEntity) && Objects.equals(contractGrossFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractGrossProfit = moneyParseThrousandth(contractGrossFieldAttrEntity,data,ContractEnum.GROSS_PROFIT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractGrossFieldAttrEntity.getAttrName() + "/" +unit, contractGrossProfit, false));
                }
                FieldAttrEntity contractGrossRateFieldAttrEntity = explainMap.get(ContractEnum.GROSS_PROFIT_RATE.getAttr());
                if (Objects.nonNull(contractGrossRateFieldAttrEntity) && Objects.equals(contractGrossRateFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    String contractGrossProfitRateStr = data.getString(ContractEnum.GROSS_PROFIT_RATE.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractGrossRateFieldAttrEntity.getAttrName() + "/%", contractGrossProfitRateStr, false));
                }
                FieldAttrEntity contractCashProfitFieldAttrEntity = explainMap.get(ContractEnum.CASH_PROFIT.getAttr());
                if (Objects.nonNull(contractCashProfitFieldAttrEntity) && Objects.equals(contractCashProfitFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractCashProfit = moneyParseThrousandth(contractCashProfitFieldAttrEntity,data,ContractEnum.CASH_PROFIT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractCashProfitFieldAttrEntity.getAttrName() + "/" +unit, contractCashProfit, false));
                }
                FieldAttrEntity contractCashProfitRateFieldAttrEntity = explainMap.get(ContractEnum.CASH_PROFIT_RATE.getAttr());
                if (Objects.nonNull(contractCashProfitRateFieldAttrEntity) && Objects.equals(contractCashProfitRateFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    String contractCashProfitRateStr = data.getString(ContractEnum.CASH_PROFIT_RATE.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractCashProfitRateFieldAttrEntity.getAttrName() + "/%", contractCashProfitRateStr, false));
                }
                break;
            case REFUND:
                FieldAttrEntity refundUnAmountFieldAttrEntity = explainMap.get(RefundEnum.RETURN_AMOUNT.getAttr());
                if (refundUnAmountFieldAttrEntity != null && Objects.equals(refundUnAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object refundUnAmount = moneyParseThrousandth(refundUnAmountFieldAttrEntity, data, RefundEnum.RETURN_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.RETURN_AMOUNT) + UnitEnum.MONEY.getName(), refundUnAmount, false));
                }
                FieldAttrEntity refundRealAmountFieldAttrEntity = explainMap.get(RefundEnum.REFUND_AMOUNT.getAttr());
                if (refundRealAmountFieldAttrEntity != null && Objects.equals(refundRealAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object refundRealAmount = moneyParseThrousandth(refundRealAmountFieldAttrEntity, data, RefundEnum.REFUND_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.REFUND_AMOUNT) + UnitEnum.MONEY.getName(), refundRealAmount, false));
                }
                break;
            case QUOTATION:
                FieldAttrEntity quotationAmountFieldAttrEntity = explainMap.get(QuotationEnum.AMOUNT.getAttr());
                String unitStr = UnitEnum.MONEY.getName();
                if (Objects.nonNull(quotationAmountFieldAttrEntity) && Objects.equals(quotationAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractAmount = moneyParseThrousandth(quotationAmountFieldAttrEntity,data,QuotationEnum.AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(quotationAmountFieldAttrEntity.getAttrName() + "/" + unitStr, contractAmount, false));
                }

                FieldAttrEntity quotationDiscountFieldAttrEntity = explainMap.get(QuotationEnum.DISCOUNT.getAttr());
                if (Objects.nonNull(quotationDiscountFieldAttrEntity) && Objects.equals(quotationDiscountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    String quotationDiscount = data.getString(QuotationEnum.DISCOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(quotationDiscountFieldAttrEntity.getAttrName() + "/%", quotationDiscount, false));
                }

                FieldAttrEntity quotationEstimateCostFieldAttrEntity = explainMap.get(QuotationEnum.ESTIMATE_COST.getAttr());
                if (Objects.nonNull(quotationEstimateCostFieldAttrEntity) && Objects.equals(quotationEstimateCostFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object estimateCost = data.getString(QuotationEnum.ESTIMATE_COST.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(quotationEstimateCostFieldAttrEntity.getAttrName() + "/" + unitStr, estimateCost ,false));
                }

                FieldAttrEntity quotationCostFieldAttrEntity = explainMap.get(QuotationEnum.ESTIMATE_COST.getAttr());
                if (Objects.nonNull(quotationCostFieldAttrEntity) && Objects.equals(quotationCostFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractCost = moneyParseThrousandth(quotationCostFieldAttrEntity,data,ContractEnum.ESTIMATE_COST.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(quotationCostFieldAttrEntity.getAttrName() + "/" + unitStr, contractCost, false));
                }
                FieldAttrEntity quotationGrossFieldAttrEntity = explainMap.get(QuotationEnum.GROSS_PROFIT.getAttr());
                if (Objects.nonNull(quotationGrossFieldAttrEntity) && Objects.equals(quotationGrossFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractGrossProfit = moneyParseThrousandth(quotationGrossFieldAttrEntity,data,QuotationEnum.GROSS_PROFIT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(quotationGrossFieldAttrEntity.getAttrName() + "/" + unitStr, contractGrossProfit, false));
                }

                FieldAttrEntity quotationGrossProfitRateFieldAttrEntity = explainMap.get(QuotationEnum.GROSS_PROFIT_RATE.getAttr());
                if (Objects.nonNull(quotationGrossProfitRateFieldAttrEntity) && Objects.equals(quotationGrossProfitRateFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    String quotaionGrossProfitRateStr = data.getString(QuotationEnum.GROSS_PROFIT_RATE.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(quotationGrossProfitRateFieldAttrEntity.getAttrName() + "/%", quotaionGrossProfitRateStr, false));
                }
                break;
            case MARKET_ACTIVITY:
                MarketActivityEffectGetDTO marketActivityEffectGetDTO = new MarketActivityEffectGetDTO();
                marketActivityEffectGetDTO.setCorpid(corpid);
                marketActivityEffectGetDTO.setDataId(dataId);
                marketActivityEffectGetDTO.setUserId(userId);
                marketActivityEffectGetDTO.setLoginUser(loginUser);
                //获取指标
                MarketActivityEffectTargetVO marketActivityEffectTargetVO = marketActivityEffectService.getMarketActivityEffectTargetVO(marketActivityEffectGetDTO);
                List<ConditionsEntityExt> allClueConditions = Arrays.asList(new ConditionsEntityExt(ClueEnum.MARKET_ACTIVITY_ID.getAttr(), "", ClueEnum.MARKET_ACTIVITY_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId)));
                //全部线索
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.ALL_CLUE_COUNT.getName(), marketActivityEffectTargetVO.getClueCount(), allClueConditions, true, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //有效线索(条件： dataId + 线索状态)
                List<ConditionsEntityExt> effectClueConditions = Arrays.asList(new ConditionsEntityExt(ClueEnum.CLUE_STATUS.getAttr(), "", ClueEnum.CLUE_STATUS.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(ClueStatusEnum.INVALID.getCode())),
                        new ConditionsEntityExt(ClueEnum.MARKET_ACTIVITY_ID.getAttr(), "", ClueEnum.MARKET_ACTIVITY_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId)));
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.EFFECTIVE_CLUE_COUNT.getName(), marketActivityEffectTargetVO.getEffectiveClueCount(), effectClueConditions , true, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //转化线索数量
                List<ConditionsEntityExt> transformedClueConditions = Arrays.asList(new ConditionsEntityExt(ClueEnum.CLUE_STATUS.getAttr(), "", ClueEnum.CLUE_STATUS.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(ClueStatusEnum.TRANSFORMED.getCode())),
                        new ConditionsEntityExt(ClueEnum.MARKET_ACTIVITY_ID.getAttr(), "", ClueEnum.MARKET_ACTIVITY_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId)));
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.TRANSFORMED_CLUE_COUNT.getName(), marketActivityEffectTargetVO.getTransformedClueCount(), transformedClueConditions , true, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                // 下面的指标都是 不需要穿透的，传输了 XbbRefTypeEnum.CLUE.getCode()，其实用不到
                //客户数量
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.CUSTOMER_COUNT.getName(), marketActivityEffectTargetVO.getCustomerCount(), null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //线索转客户转化率
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.CLUE_CUSTOMER_RATE.getName(), marketActivityEffectTargetVO.getClueCustomerRate()+"%", null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //机会数量
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.ALL_OPPORTUNITY_COUNT.getName(), marketActivityEffectTargetVO.getAllOpportunityCount(), null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //机会金额
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.ALL_OPPORTUNITY_AMOUNT.getName(), marketActivityEffectTargetVO.getAllOpportunityAmount(), null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //线索转机会转化率
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.CLUE_OPPORTUNITY_RATE.getName(), marketActivityEffectTargetVO.getClueOpportunityRate()+"%", null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //赢单机会数量
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.WIN_OPPORTUNITY_COUNT.getName(), marketActivityEffectTargetVO.getWinOpportunityCount(), null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                //赢单机会金额
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.WIN_OPPORTUNITY_AMOUNT.getName(), marketActivityEffectTargetVO.getWinOpportunityAmount(), null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));

                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.ALL_CONTRACT_COUNT.getName(),String.valueOf(marketActivityEffectTargetVO.getAllContractCount()),null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.ALL_CONTRACT_AMOUNT.getName(),String.valueOf(marketActivityEffectTargetVO.getAllContractAmount()),null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));
                moneyItemList.add(new MobileDetailMoneyItemPojo(MarketActivityEffectTargetEnum.CLUE_CONTRACT_RATE.getName(),String.valueOf(marketActivityEffectTargetVO.getClueContractRate()+"%"),null, false, XbbRefTypeEnum.CLUE.getCode(), BasicConstant.ONE));

                break;
            case ORDER:
                contractAmountFieldAttrEntity = explainMap.get(OrderEnum.AMOUNT.getAttr());
                unit = UnitEnum.MONEY.getName();
                if (Objects.nonNull(contractAmountFieldAttrEntity) && Objects.equals(contractAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractAmount = moneyParseThrousandth(contractAmountFieldAttrEntity,data,OrderEnum.AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractAmountFieldAttrEntity.getAttrName() + "/" +unit, contractAmount, false));
                }
                finishAmountFieldAttrEntity = explainMap.get(OrderEnum.FINISH_AMOUNT.getAttr());
                if (Objects.nonNull(finishAmountFieldAttrEntity) && Objects.equals(finishAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object finishAmount = moneyParseThrousandth(finishAmountFieldAttrEntity,data,OrderEnum.FINISH_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_COLLECTED) + unit, finishAmount, false));
                }
                unfinishAmountFieldAttrEntity = explainMap.get(OrderEnum.UN_FINISH_AMOUNT.getAttr());
                if (Objects.nonNull(unfinishAmountFieldAttrEntity) && Objects.equals(unfinishAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object unFinishAmount = moneyParseThrousandth(unfinishAmountFieldAttrEntity,data,OrderEnum.UN_FINISH_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.UNPAID_AMOUNT_OTHER) + unit, unFinishAmount, false));
                }
                badAmountFieldAttrEntity = explainMap.get(OrderEnum.BAD_AMOUNT.getAttr());
                if (Objects.nonNull(badAmountFieldAttrEntity) && Objects.equals(badAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object badAmount = moneyParseThrousandth(badAmountFieldAttrEntity,data,OrderEnum.BAD_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT_OF_BAD_DEBTS) + unit, badAmount, false));
                }
                contractCostFieldAttrEntity = explainMap.get(OrderEnum.ORDER_COST.getAttr());
                if (Objects.nonNull(contractCostFieldAttrEntity) && Objects.equals(contractCostFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractCost = moneyParseThrousandth(contractCostFieldAttrEntity,data,OrderEnum.ORDER_COST.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractCostFieldAttrEntity.getAttrName() + "/" +unit, contractCost, false));
                }
                contractGrossFieldAttrEntity = explainMap.get(OrderEnum.GROSS_PROFIT.getAttr());
                if (Objects.nonNull(contractGrossFieldAttrEntity) && Objects.equals(contractGrossFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractGrossProfit = moneyParseThrousandth(contractGrossFieldAttrEntity,data,OrderEnum.GROSS_PROFIT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractGrossFieldAttrEntity.getAttrName() + "/" +unit, contractGrossProfit, false));
                }
                contractGrossRateFieldAttrEntity = explainMap.get(OrderEnum.GROSS_PROFIT_RATE.getAttr());
                if (Objects.nonNull(contractGrossRateFieldAttrEntity) && Objects.equals(contractGrossRateFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    String contractGrossProfitRateStr = data.getString(OrderEnum.GROSS_PROFIT_RATE.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractGrossRateFieldAttrEntity.getAttrName() + "/%", contractGrossProfitRateStr, false));
                }
                contractCashProfitFieldAttrEntity = explainMap.get(OrderEnum.CASH_PROFIT.getAttr());
                if (Objects.nonNull(contractCashProfitFieldAttrEntity) && Objects.equals(contractCashProfitFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object contractCashProfit = moneyParseThrousandth(contractCashProfitFieldAttrEntity,data,OrderEnum.CASH_PROFIT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractCashProfitFieldAttrEntity.getAttrName() + "/" +unit, contractCashProfit, false));
                }
                contractCashProfitRateFieldAttrEntity = explainMap.get(OrderEnum.CASH_PROFIT_RATE.getAttr());
                if (Objects.nonNull(contractCashProfitRateFieldAttrEntity) && Objects.equals(contractCashProfitRateFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    String contractCashProfitRateStr = data.getString(OrderEnum.CASH_PROFIT_RATE.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(contractCashProfitRateFieldAttrEntity.getAttrName() + "/%", contractCashProfitRateStr, false));
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
                // 跟进次数
                List<PaasFormDataEntityExt> distributorCommunicateList = customerCommunicateService.getCustomerCommunicateEsDataListByCustomerId(corpid, dataId);
                Integer distributorCommunicateCount = Objects.isNull(distributorCommunicateList) ? 0 : distributorCommunicateList.size();
                moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.FOLLOW_UP_TIMES), distributorCommunicateCount, false));
                FormDataListDTO dataListDTO = new FormDataListDTO();
                dataListDTO.setUserId(userId);
                dataListDTO.setCorpid(corpid);
                dataListDTO.setExplainMap(explainMap);
                // 订货单
                List<PaasFormDataEntityExt> orderList = contractService.getContractEsDataListByCustomerId(corpid, dataId);
                if (Objects.nonNull(orderList)) {
                    AtomicReference<Double> totalAmount = new AtomicReference<>(0D);
                    orderList.forEach(contract -> {
                        JSONObject contractData = contract.getData();
                        Double amountMoney = StringUtil.toDouble(contractData.getString(ContractEnum.AMOUNT.getAttr()), 0D);
                        totalAmount.set(Arith.add(totalAmount.get(), amountMoney));
                    });
                    // 订货单金额处理为千份位
                    Object orderAmount = AttrDecimalPrecisionHelper.parseThousandth(totalAmount.get(), accuracy);
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.ORDER_AMOUNT), orderAmount, false));
                    List<ConditionsEntityExt> contractCondictions = new ArrayList<>();
                    ConditionsEntityExt contractCondiction = new ConditionsEntityExt(ContractEnum.LINK_CUSTOMER.getAttr(), "", ContractEnum.LINK_CUSTOMER.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                    contractCondictions.add(contractCondiction);
                    contractCondictions.add(EsUtil.packageContions(ContractEnum.IS_RED.getAttr(), Collections.singletonList(0), ConditionEnum.EQUAL, ContractEnum.IS_RED.getFieldType()));
                    moneyItemList.add(new MobileDetailMoneyItemPojo(distributorMark, I18nMessageUtil.getMessage(I18nStringConstant.ORDER), orderList.size(), contractCondictions, true, XbbRefTypeEnum.CONTRACT.getCode(), BasicConstant.ONE));
                }
                // 回款总额
                List<String> codeListForDistributorSum = PaymentSheetTypeEnum.getCodeListForCustomerSum();
                List<PaasFormDataEntityExt> paymentSheetEsDataList = paymentSheetService.getPaymentSheetEsDataListByCustomerId(corpid, dataId, codeListForDistributorSum, loginUser);
                if (Objects.nonNull(paymentSheetEsDataList)) {
                    AtomicReference<Double> paymentAmountByOrder = new AtomicReference<>(0D);
                    paymentSheetEsDataList.forEach(payment -> {
                        JSONObject paymentData = payment.getData();
                        Double totalAmount = StringUtil.toDouble(paymentData.getString(PaymentSheetEnum.AMOUNT.getAttr()), 0D);
                        paymentAmountByOrder.set(Arith.add(paymentAmountByOrder.get(), totalAmount));
                    });
                    String paymentTotalByOrder = attrDecimalPrecisionHelper.formatMoneyPrecision(paymentAmountByOrder.get(), accuracy);
                    List<ConditionsEntityExt> paymentCondictionsByOrder = new ArrayList<>();
                    ConditionsEntityExt paymentCondictionByOrder = new ConditionsEntityExt(PaymentSheetEnum.CUSTOMER_ID.getAttr(), "", PaymentSheetEnum.CUSTOMER_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                    paymentCondictionsByOrder.add(paymentCondictionByOrder);
                    moneyItemList.add(new MobileDetailMoneyItemPojo(distributorMark, I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_REFUND), paymentTotalByOrder, paymentCondictionsByOrder, true, XbbRefTypeEnum.PAYMENT_SHEET.getCode(), BasicConstant.ONE));
                }
                //应收未收
                List<PaasFormDataEntityExt> paymentListByOrder = paymentService.getPaymentEsDataListByCustomerId(corpid, dataId);
                AtomicReference<Double> paymentAmountByOrder = new AtomicReference<>(0D);
                paymentListByOrder.forEach(payment -> {
                    JSONObject paymentData = payment.getData();
                    Double totalAmount = StringUtil.toDouble(paymentData.getString(PaymentEnum.UN_AMOUNT.getAttr()), 0D);
                    paymentAmountByOrder.set(Arith.add(paymentAmountByOrder.get(), totalAmount));
                });
                String paymentTotalByOrder = attrDecimalPrecisionHelper.formatMoneyPrecision(paymentAmountByOrder.get(), accuracy);
                List<ConditionsEntityExt> paymentCondictionsByOrder = new ArrayList<>();
                ConditionsEntityExt paymentCondictionByOrder = new ConditionsEntityExt(PaymentEnum.CUSTOMER.getAttr(), "", PaymentEnum.CUSTOMER.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(dataId));
                paymentCondictionsByOrder.add(paymentCondictionByOrder);
                moneyItemList.add(new MobileDetailMoneyItemPojo(distributorMark, I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_PAYMENT), paymentTotalByOrder, paymentCondictionsByOrder, true, XbbRefTypeEnum.PAYMENT.getCode(), BasicConstant.ONE));
                break;
            case RETURN:
                refundUnAmountFieldAttrEntity = explainMap.get(ReturnEnum.RETURN_AMOUNT.getAttr());
                if (refundUnAmountFieldAttrEntity != null && Objects.equals(refundUnAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object refundUnAmount = moneyParseThrousandth(refundUnAmountFieldAttrEntity, data, ReturnEnum.RETURN_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.RETURN_AMOUNT) + UnitEnum.MONEY.getName(), refundUnAmount, false));
                }
                refundRealAmountFieldAttrEntity = explainMap.get(ReturnEnum.REFUND_AMOUNT.getAttr());
                if (refundRealAmountFieldAttrEntity != null && Objects.equals(refundRealAmountFieldAttrEntity.getVisible(), BasicConstant.ONE)) {
                    Object refundRealAmount = moneyParseThrousandth(refundRealAmountFieldAttrEntity, data, ReturnEnum.REFUND_AMOUNT.getAttr());
                    moneyItemList.add(new MobileDetailMoneyItemPojo(I18nMessageUtil.getMessage(I18nStringConstant.REFUND_AMOUNT) + UnitEnum.MONEY.getName(), refundRealAmount, false));
                }
                break;
            default:
                break;
        }
        return moneyItemList;
    }

    private Object moneyParseThrousandth(FieldAttrEntity fieldAttrEntity,JSONObject data,String attr){
        return AttrDecimalPrecisionHelper.moneyParseThrousandth(fieldAttrEntity, data, attr);
    }

    /**
     * 获取移动端详情页底部操作按钮
     *
     * @return List
     * @author GuoJun.HU
     * @date 2019/4/16 14:40
     * @since V1.0
     */
    @Override
    public List<TopPermissionsPoJo> getMobileDetailBottomOperation(Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, UserVO userVO) throws XbbException {
        HandelDetailPojo handelDetailPojo = new HandelDetailPojo(null, businessType, paasFormDataEntityExt, userVO);
        return getMobileDetailBottomOperation(handelDetailPojo);
    }

    @Override
    public List<TopPermissionsPoJo> getMobileDetailBottomOperation(HandelDetailPojo handelDetailPojo) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        Integer businessType4Distributor = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, handelDetailPojo.getDistributorMark());
        PaasFormDataEntityExt paasFormDataEntityExt = handelDetailPojo.getPaasFormDataEntityExt();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer distributorMark = handelDetailPojo.getDistributorMark();
        List<TopPermissionsPoJo> bottomOperationList = new ArrayList<>();
        List<MobileDetailBottomOperationEnum> bottomOperationEnumList = MobileDetailBottomOperationEnum.getByBusinessTypeAndPermission(businessType4Distributor, userVO.getPermSet());
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType4Distributor);
        switch (redundantTemplateTypeEnum) {
            case PAY_PLAN:
                String status = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UNKNOWN.getCode());
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    if (Objects.equals(status, PayPlanStatusEnum.RECEIVABLES.getCode()) && Objects.equals(anEnum, MobileDetailBottomOperationEnum.PAY_PLAN_SHEET)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
            case PAYMENT:
                status = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getCode());
                Double invoiceMoney = getDoubleOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaymentEnum.INVOICE_AMOUNT.getAttr(), 0D);
                Double paymentMoney = getDoubleOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaymentEnum.AMOUNT.getAttr(), 0D);
                List<String> invoiceStatus = new ArrayList<>();
                invoiceStatus.add(PaymentStatusEnum.UN_RECEIVABLES.getCode());
                invoiceStatus.add(PaymentStatusEnum.PARTIAL_RECEIPTS.getCode());
                invoiceStatus.add(PaymentStatusEnum.RECEIVABLES.getCode());
                boolean notItemInvoice = invoiceMoney >= paymentMoney || !invoiceStatus.contains(status);
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    boolean notItemSheet = !(Objects.equals(status, PaymentStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(status, PaymentStatusEnum.PARTIAL_RECEIPTS.getCode())) && Objects.equals(anEnum, MobileDetailBottomOperationEnum.PAYMENT_PAYMENT_SHEET);
                    if (notItemSheet) {
                        continue;
                    }
                    if (notItemInvoice && Objects.equals(anEnum, MobileDetailBottomOperationEnum.PAYMENT_INVOICE)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
            case COMMUNICATE_PLAN:
                String communicatePlanStatus = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CommunicatePlanEnum.STATUS.getAttr(), CommunicatePlanStatusEnum.UNKNOW.getCode());
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    if (Objects.equals(communicatePlanStatus, CommunicatePlanStatusEnum.FINISH.getCode()) && Objects.equals(anEnum, MobileDetailBottomOperationEnum.COMMUNICATE_PLAN_FINISH)) {
                        continue;
                    }
                    if (Objects.equals(communicatePlanStatus, CommunicatePlanStatusEnum.CANCEL.getCode()) && Objects.equals(anEnum, MobileDetailBottomOperationEnum.COMMUNICATE_PLAN_CANCLE)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
            case CUSTOMER:
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
            case WORKORDER:
                JSONArray phoneAttr = FastJsonHelper.getJsonArrOrDefaultFromFormData(paasFormDataEntityExt.getData(), WorkOrderEnum.CONTACT_INFORMATION.getAttr(), new JSONArray());
                if (phoneAttr.isEmpty()) {
                    bottomOperationEnumList.remove(MobileDetailBottomOperationEnum.WORK_ORDER_CONTACT);
                }
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
            case PAYMENT_TASK:
                String paymentTaskStatus = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaymentTaskEnum.STATUS.getAttr(), PaymentTaskStatusEnum.UNKNOW.getCode());
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    if (Objects.equals(paymentTaskStatus, PaymentTaskStatusEnum.FINISH.getCode()) && Objects.equals(anEnum, MobileDetailBottomOperationEnum.PAYMENT_TASK_FINISH)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
            default:
                for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    bottomOperationList.add(topPermissionsPoJo);
                }
                break;
        }
        return bottomOperationList;
    }

    @Override
    public BaseVO setReadMessage(ReadMessageSetDTO readMessageSetDTO) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, readMessageSetDTO.getCorpid());
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.USER_ID, readMessageSetDTO.getUserId());
        param.put("refId", readMessageSetDTO.getDataId());
        param.put("pushId", readMessageSetDTO.getPushId());
        if (Objects.equals(readMessageSetDTO.getIsRemind(), BasicConstant.ONE)) {
            param.put("isRemind", readMessageSetDTO.getIsRemind());
        }
        Integer businessType = readMessageSetDTO.getBusinessType();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        List<Integer> refEntityIn = new ArrayList<>();
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                refEntityIn.add(RefEntityEnum.CUSTOMER_ENTITY.getCode());
                refEntityIn.add(RefEntityEnum.CUSTOMER_BACK_REMIND.getCode());
                refEntityIn.add(RefEntityEnum.CUSTOMER_STAGE.getCode());
                break;
            case CONTRACT:
                refEntityIn.add(RefEntityEnum.CONTRACT_ENTITY.getCode());
                refEntityIn.add(RefEntityEnum.CONTRACT_REMIND.getCode());
                break;
            case SALES_OPPORTUNITY:
                refEntityIn.add(RefEntityEnum.SALES_OPPORTUNITY_ENTITY.getCode());
                break;
            case SUPPLIER:
                refEntityIn.add(RefEntityEnum.SUPPLIER_ENTITY.getCode());
                break;
            case PURCHASE:
                refEntityIn.add(RefEntityEnum.PURCHASE_ENTITY.getCode());
                break;
            case QUOTATION:
                refEntityIn.add(RefEntityEnum.QUOTATION.getCode());
                break;
            case CLUE:
                refEntityIn.add(RefEntityEnum.CLUE_ENTITY.getCode());
                refEntityIn.add(RefEntityEnum.CLUE_BACK_REMIND.getCode());
                refEntityIn.add(RefEntityEnum.CLUE_STAGE.getCode());
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        param.put("refEntityIn", refEntityIn);
        pushLinkModel.readAllPushLink(param);
        return new BaseVO();
    }

    @Override
    public ResultThroughVO getDetailThrough(MobileDetailThroughDTO mobileDetailThroughDTO ) throws XbbException {

        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(mobileDetailThroughDTO, formDataListDTO);
        ResultThroughVO resultThroughVO = new ResultThroughVO();
        Integer businessType = mobileDetailThroughDTO.getBusinessType();
        Integer subBusinessType = mobileDetailThroughDTO.getSubBusinessType();
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER.getCode(), subBusinessType)) {
            subBusinessType = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode();
        }
        Integer page = mobileDetailThroughDTO.getPage();
        Integer pageSize = mobileDetailThroughDTO.getPageSize();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        Integer distributorMark = mobileDetailThroughDTO.getDistributorMark();
        // 菜单名影响
        PaasMenuEntity menuEntity;
        if (DistributorMarkEnum.DISTRIBUTOR.getCode().equals(distributorMark) && !FormTypeEnum.isMultiSingleTemplate(businessType)) {
            menuEntity = paasMenuModel.getByAlias4Distributor(XbbRefTypeEnum.getByCode(businessType).getAlias(), mobileDetailThroughDTO.getCorpid(), distributorMark);
        } else {
            menuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.getByCode(businessType).getAlias(), mobileDetailThroughDTO.getCorpid());
        }
        // 增加下这个，否则会报错
        TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), mobileDetailThroughDTO.getBusinessType(), menuEntity.getId(), mobileDetailThroughDTO.getDistributorMark());
        resultThroughVO.setHead(menuEntity.getName());
        resultThroughVO.setDistributorMark(distributorMark);
        PaasFormDataEsListVO paasFormDataEsListVO;
        ListAppVO listAppVO;
        Integer totalCount;
        List<PaasFormDataEntityExt> esEntities;
        Integer fromBusinessType = mobileDetailThroughDTO.getFromBusinessType();
        UserVO userVO = mobileDetailThroughDTO.getLoginUser();
        switch (redundantTemplateTypeEnum) {
            case CONTRACT:
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(mobileDetailThroughDTO.getCorpid(), businessType, SaasMarkEnum.SAAS.getCode());
                EsUtil.parseCondition(boolQueryBuilder, mobileDetailThroughDTO.getConditions(), mobileDetailThroughDTO.getRel(), mobileDetailThroughDTO.getCorpid(), businessType);
                boolQueryBuilder.filter(termQuery("corpid.keyword", mobileDetailThroughDTO.getCorpid()));
                boolQueryBuilder.filter(termQuery("del", 0));
                boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
                if(Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),fromBusinessType)){
                    boolQueryBuilder.filter(rangeQuery(ContractEnum.getAttrConnectData(ContractEnum.UN_FINISH_AMOUNT)).gt(0));
                    Long customerId = mobileDetailThroughDTO.getAssociationId();
                    if(customerId == null){
                        throw new XbbException(ContractErrorCodeEnum.API_ERROR_203015);
                    }
                    boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.LINK_CUSTOMER),customerId));
                    boolQueryBuilder.filter(termQuery(ContractEnum.getAttrConnectData(ContractEnum.IS_RED),0));
                }
                UserEntity userEntity = new UserEntity();
                BeanUtil.copyProperties(userVO, userEntity);
                Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.CONTRACT.getCode(), 0L);
                List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ONE,false);
                HasChildQueryBuilder hasChildQueryBuilder = esHelper.teamQueryBuilder(IndexTypeEnum.IDX_SAAS_CONTRACT_TEAM , userVO.getCorpid(), null, userIdIn);
                boolQueryBuilder.must(hasChildQueryBuilder);
                //分页查询
                XbbAggregatedPage entitys = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, PaasFormDataEntityExt.class, null, page, pageSize, Collections.singletonList(new FieldSortBuilder(StringConstant.ADD_TIME).order(SortOrder.DESC)));
                int rowCounts = 0;
                List list = new ArrayList<>();
                if (entitys != null) {
                    rowCounts = (int) entitys.getTotalElements();
                    list = entitys.getContent();
                }
                PageHelper pageHelper = PageHelperUtil.initPageHelper(rowCounts, page, pageSize, PageConstant.DEFAULT_PAGE_SIZE);
                resultThroughVO.setPageHelper(pageHelper);
                //封装移动端端结果
                resultThroughVO = formatList(mobileDetailThroughDTO, list, resultThroughVO);
                break;
            case SALES_OPPORTUNITY:
                formDataListDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.ALL_OPPORTUNITY.getCode());
                //要把主业务的formId移除掉，因为这边的formId是主业务的formId，要移除掉
                formDataListDTO.setFormId(null);
                listAppVO = commonDingtalkListQry.dingtalkExecute(formDataListDTO);
                resultThroughVO.setDataApp(listAppVO);
                resultThroughVO.setPageHelper(listAppVO.getPageHelper());
                // resultThroughVO.setHead(redundantTemplateTypeEnum.getName());
                resultThroughVO.setBusinessType(businessType);
                break;
            case PAYMENT:
                //boolQueryBuilder.filter(termsQuery("data." + PaymentEnum.STATUS.getAttr(), Arrays.asList(PaymentStatusEnum.UN_RECEIVABLES.getCode(), PaymentStatusEnum.PARTIAL_RECEIPTS.getCode())));
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
                //要把主业务的formId移除掉，因为这边的formId是主业务的formId，要移除掉
                formDataListDTO.setFormId(null);
                if ( formDataListDTO.getSortMap().isEmpty() ) {
                    Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    sortMap.put(PaymentEnum.UPDATE_TIME.getAttr(), "desc");
                    formDataListDTO.setSortMap(sortMap);
                }
                paasFormDataEsListVO = saasListService.paymentList(formDataListDTO);
                esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                if (totalCount != null && totalCount != 0) {
                    listAppVO = paymentService.formatPaymentAppList(formDataListDTO, esEntities, totalCount);
                    resultThroughVO.setDataApp(listAppVO);
                    resultThroughVO.setPageHelper(paasFormDataEsListVO.getPageHelper());
                }
                // resultThroughVO.setHead(redundantTemplateTypeEnum.getName());
                resultThroughVO.setBusinessType(businessType);
                break;
            case PURCHASE:
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
                //要把主业务的formId移除掉，因为这边的formId是主业务的formId，要移除掉
                formDataListDTO.setFormId(null);
                Long supplierId = mobileDetailThroughDTO.getAssociationId();
                if(supplierId == null){
                    throw new XbbException(PurchaseErrorCodeEnum.API_ERROR_225034);
                }
                packagePurchaseConditions(formDataListDTO, fromBusinessType, supplierId);
                paasFormDataEsListVO = saasListService.purchaseList(formDataListDTO);
                esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                if (totalCount != null && totalCount != 0) {
                    listAppVO = formatPurchaseAppList(esEntities, totalCount);
                    resultThroughVO.setDataApp(listAppVO);
                    resultThroughVO.setPageHelper(paasFormDataEsListVO.getPageHelper());
                }
                // resultThroughVO.setHead(redundantTemplateTypeEnum.getName());
                resultThroughVO.setBusinessType(businessType);
                break;
            case QUOTATION:
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.QUOTATION.getCode());
                //要把主业务的formId移除掉，因为这边的formId是主业务的formId，要移除掉
                formDataListDTO.setFormId(null);
                listAppVO = commonDingtalkListQry.dingtalkExecute(formDataListDTO);
                resultThroughVO.setDataApp(listAppVO);
                resultThroughVO.setPageHelper(listAppVO.getPageHelper());
                // resultThroughVO.setHead(redundantTemplateTypeEnum.getName());
                resultThroughVO.setBusinessType(businessType);
                break;
            case PAYMENT_SHEET:
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.PAYMENT_SHEET.getCode());
                //要把主业务的formId移除掉，因为这边的formId是主业务的formId，要移除掉
                formDataListDTO.setFormId(null);
                List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
                conditions.add(EsUtil.packageContions(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), new ArrayList<>(PaymentSheetTypeEnum.getCodeListForCustomer()), ConditionEnum.IN, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getFieldType()));
                //客户tab内回款单穿透不限制人员（核心只限制客户id）
                formDataListDTO.setThrough(true);
                paasFormDataEsListVO = saasListService.paymentSheetList(formDataListDTO);
                esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                if (totalCount != null && totalCount != 0) {
                    listAppVO = paymentSheetService.formatPaymentSheetAppList(formDataListDTO, esEntities, totalCount);
                    resultThroughVO.setDataApp(listAppVO);
                    resultThroughVO.setPageHelper(paasFormDataEsListVO.getPageHelper());
                }
                // resultThroughVO.setHead(redundantTemplateTypeEnum.getName());
                resultThroughVO.setBusinessType(businessType);
                break;
            case ONLINE_PAYMENT_FLOW:
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getCode());
                //要把主业务的formId移除掉，因为这边的formId是主业务的formId，要移除掉
                formDataListDTO.setFormId(null);
                paasFormDataEsListVO = saasListService.onlinePaymentFlowList(formDataListDTO);
                esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                if (totalCount != null && totalCount != 0) {
                    listAppVO = onlinePaymentFlowService.formatOnlinePaymentFlowAppList(formDataListDTO, esEntities, totalCount);
                    resultThroughVO.setDataApp(listAppVO);
                    resultThroughVO.setPageHelper(paasFormDataEsListVO.getPageHelper());
                }
                // resultThroughVO.setHead(redundantTemplateTypeEnum.getName());
                resultThroughVO.setBusinessType(businessType);
                break;
            case CLUE:
                RelationSaleClueListDTO relationSaleClueListDTO = new RelationSaleClueListDTO();
                //要把主业务的formId移除掉，因为这边的formId是主业务的formId，要移除掉
                formDataListDTO.setFormId(null);
                BeanUtil.copyProperties(formDataListDTO,relationSaleClueListDTO);
                RelationSaleClueListVO relationSaleClueListVO = getAppRelationSaleClueList(relationSaleClueListDTO);
                resultThroughVO.setPageHelper(relationSaleClueListVO.getPageHelper());
                resultThroughVO.setDataApp(relationSaleClueListVO.getDataApp());
                resultThroughVO.setBusinessType(relationSaleClueListVO.getBusinessType());
                break;
            default:
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return resultThroughVO;
    }

    @Override
    public RelationSaleClueListVO getAppRelationSaleClueList(RelationSaleClueListDTO relationSaleClueListDTO) throws XbbException {
        RelationSaleClueListVO relationSaleClueListVO = new RelationSaleClueListVO();
        XbbAggregatedPage relationSaleClueList = saasGetHelp.getRelationSaleClueList(relationSaleClueListDTO);
        //分页查询
        int rowCounts = 0;
        List list = new ArrayList<>();
        if (relationSaleClueList != null) {
            rowCounts = (int) relationSaleClueList.getTotalElements();
            list = relationSaleClueList.getContent();
            //对字段进行处理
            saasGetHelp.analysisClueDataList(list,relationSaleClueListDTO);

        }
        PageHelper pageHelper = PageHelperUtil.initPageHelper(rowCounts, relationSaleClueListDTO.getPage(), relationSaleClueListDTO.getPageSize(), PageConstant.DEFAULT_PAGE_SIZE);
        relationSaleClueListVO.setPageHelper(pageHelper);
        //封装移动端端结果
        relationSaleClueListVO = formatRelationSaleClue4App(relationSaleClueListDTO.getCorpid(), list, relationSaleClueListVO);
        return relationSaleClueListVO;
    }

    private RelationSaleClueListVO formatRelationSaleClue4App(String corpid, List<PaasFormDataEntityExt> list, RelationSaleClueListVO relationSaleClueListVO) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        JSONObject defaultJson = new JSONObject();
        for(PaasFormDataEntityExt marketActivityEntity : list){
            long id = marketActivityEntity.getDataId();
            long appId = marketActivityEntity.getAppId();
            long menuId = marketActivityEntity.getMenuId();
            long formId = marketActivityEntity.getFormId();
            JSONObject data = marketActivityEntity.getData();
            if(Objects.nonNull(data)){
                //数据标题： 线索名称
                List<Object> nameValue = Arrays.asList(data.get(ClueEnum.COMPANY_NAME.getAttr()));
                List<FormTitlePoJo> titleList = Arrays.asList(new FormTitlePoJo(ClueEnum.COMPANY_NAME.getAttr(),"",ClueEnum.COMPANY_NAME.getAttrName(),nameValue,""));

                //数据摘要： 负责人+创建时间(创建时间格式是时间戳的 需要格式化一下, 时间戳存进去是 10位数，所以这里要 *1000 ，才能正常转为13位的去格式化)
                List<Object> ownerValue = Arrays.asList(data.get(ClueEnum.OWNER_ID.getAttr()));
                String addTime = data.getString(ClueEnum.ADD_TIME.getAttr());
                addTime = StringUtil.isEmpty(addTime) ? "" : DateUtil.getString(Long.parseLong(addTime)*1000L);
                List<Object> addTimeValue = Arrays.asList(addTime);
                List<SummaryDataPoJo> summaryList = Arrays.asList(new SummaryDataPoJo(ClueEnum.OWNER_ID.getAttr(),ClueEnum.OWNER_ID.getAttrName(),ClueEnum.OWNER_ID.getFieldType(),ownerValue),new SummaryDataPoJo(ClueEnum.ADD_TIME.getAttr(),ClueEnum.ADD_TIME.getAttrName(),ClueEnum.ADD_TIME.getFieldType(),addTimeValue));

                //数据标签：线索状态
                List<Object> clueStatuValue = Arrays.asList(data.get(ClueEnum.CLUE_STATUS.getAttr()));
                List<SummaryDataPoJo> lablesList = Arrays.asList(new SummaryDataPoJo(ClueEnum.CLUE_STATUS.getAttr(),ClueEnum.CLUE_STATUS.getAttrName(),ClueEnum.CLUE_STATUS.getFieldType(),clueStatuValue));
                appListPojos.add(new AppListPojo(id, titleList, summaryList, defaultJson, lablesList, defaultJson, appId, menuId, formId));
            }

        }
        ListAppVO listAppVo = new ListAppVO(appListPojos, relationSaleClueListVO.getPageHelper().getRowsCount());
        relationSaleClueListVO.setDataApp(listAppVo);
        relationSaleClueListVO.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
        relationSaleClueListVO.setSubBusinessType(XbbRefTypeEnum.CLUE.getCode());
        relationSaleClueListVO.setSaasMark(1);
        return relationSaleClueListVO;
    }


    /**
     * 处理回款计划标签
     *
     * @param labelsList
     * @param data
     */
    @Override
    public void handlePaymentTask(List<SummaryDataPoJo> labelsList, JSONObject data) {
        if (data.containsKey(PaymentTaskEnum.STATUS.getAttr())) {
            if (Objects.equals(data.get(PaymentTaskEnum.STATUS.getAttr()), PaymentTaskStatusEnum.NO_FINISH.getCode())){
                SummaryDataPoJo poJo = new SummaryDataPoJo();
                poJo.setAttr(PaymentTaskEnum.STATUS.getAttr());
                poJo.setSaasAttr(PaymentTaskEnum.STATUS.getSaasAttr());
                poJo.setValue(Collections.singletonList(PaymentTaskStatusEnum.NO_FINISH.getAlias()));
                poJo.setAttrName(PaymentTaskEnum.STATUS.getAttrName());
                poJo.setFieldType(PaymentTaskEnum.STATUS.getFieldType());
                //产品说状态字段要放在最前面
                labelsList.add(BasicConstant.ZERO,poJo);
            } else if ((Objects.equals(data.get(PaymentTaskEnum.STATUS.getAttr()), PaymentTaskStatusEnum.FINISH.getCode()))) {
                SummaryDataPoJo poJo = new SummaryDataPoJo();
                poJo.setAttr(PaymentTaskEnum.STATUS.getAttr());
                poJo.setSaasAttr(PaymentTaskEnum.STATUS.getSaasAttr());
                poJo.setValue(Collections.singletonList(PaymentTaskStatusEnum.FINISH.getAlias()));
                poJo.setAttrName(PaymentTaskEnum.STATUS.getAttrName());
                poJo.setFieldType(PaymentTaskEnum.STATUS.getFieldType());
                //产品说状态字段要放在最前面
                labelsList.add(BasicConstant.ZERO,poJo);
            }
        }
    }

    @Override
    public SingleDataMessageGetVO getSingleDataMessage(SingleDataMessageGetDTO singleDataMessageGetDTO) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, singleDataMessageGetDTO.getCorpid());
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.START, singleDataMessageGetDTO.getPage());
        param.put(ParameterConstant.PAGE_NUM, 10);
        param.put("refId", singleDataMessageGetDTO.getDataId());
        Integer updateButtonShow = 0;
        if (Objects.equals(singleDataMessageGetDTO.getIsRemind(), BasicConstant.ONE)) {
            param.put("startPushTime", DateTimeUtil.getInt());
            param.put("isRemind", singleDataMessageGetDTO.getIsRemind());
            //因为“未推送的提醒”需要展示编辑，删除按钮
            updateButtonShow = 1;
        } else {
            param.put(ParameterConstant.USER_ID, singleDataMessageGetDTO.getUserId());
            param.put("endPushTime",  DateTimeUtil.getInt());
        }
        Integer businessType = singleDataMessageGetDTO.getBusinessType();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        List<Integer> refEntityIn = new ArrayList<>();
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                refEntityIn.add(RefEntityEnum.CUSTOMER_ENTITY.getCode());
                refEntityIn.add(RefEntityEnum.CUSTOMER_BACK_REMIND.getCode());
                refEntityIn.add(RefEntityEnum.CUSTOMER_STAGE.getCode());
                break;
            case CONTRACT:
                refEntityIn.add(RefEntityEnum.CONTRACT_ENTITY.getCode());
                refEntityIn.add(RefEntityEnum.CONTRACT_REMIND.getCode());
                break;
            case SALES_OPPORTUNITY:
                refEntityIn.add(RefEntityEnum.SALES_OPPORTUNITY_ENTITY.getCode());
                break;
            case SUPPLIER:
                refEntityIn.add(RefEntityEnum.SUPPLIER_ENTITY.getCode());
                break;
            case PURCHASE:
                refEntityIn.add(RefEntityEnum.PURCHASE_ENTITY.getCode());
                break;
            case QUOTATION:
                refEntityIn.add(RefEntityEnum.QUOTATION.getCode());
                break;
            case CLUE:
                refEntityIn.add(RefEntityEnum.CLUE_ENTITY.getCode());
                refEntityIn.add(RefEntityEnum.CLUE_BACK_REMIND.getCode());
                refEntityIn.add(RefEntityEnum.CLUE_STAGE.getCode());
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        param.put("refEntityIn", refEntityIn);
        PageHelper pageHelper = PageHelperUtil.getPageHelper(param, pushLinkModel, singleDataMessageGetDTO.getPageSize());
        List<PushLinkEntity> pushLinkEntityList = (List<PushLinkEntity>) PageHelperUtil.getEntityList(param, pageHelper, pushLinkModel);
        List<PushEntity> pushList = messageListService.formatPushList(pushLinkEntityList, null, singleDataMessageGetDTO.getCorpid(), singleDataMessageGetDTO.getIsRemind());
        List<MessagePojo> messagePojoList = new ArrayList<>();
        for (PushEntity pushEntity : pushList) {
            MessagePojo messagePojo = new MessagePojo();
            BeanUtil.copyProperties(pushEntity, messagePojo, true);
            messagePojo.setId(pushEntity.getId());
            messagePojo.setMsg(JSON.parseObject(pushEntity.getMsg()));
            messagePojo.setRefType(JSON.parseObject(pushEntity.getRefType()));
            messagePojo.setPushLinkId(pushEntity.getPushLinkId());
            messagePojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
            messagePojoList.add(messagePojo);
        }
        SingleDataMessageGetVO singleDataMessageGetVO = new SingleDataMessageGetVO();
        singleDataMessageGetVO.setPageHelper(pageHelper);
        singleDataMessageGetVO.setList(messagePojoList);
        singleDataMessageGetVO.setCount(pageHelper.getRowsCount());
        singleDataMessageGetVO.setUpdateButtonShow(updateButtonShow);
        singleDataMessageGetVO.setWorkFlowList(Collections.singletonList(new TabWorkFlowPojo(businessType,"pushNotify", I18nMessageUtil.getMessage(I18nStringConstant.NEW_FOLLOW_UP_ALERT), OperateTypeEnum.NEW.getAlias(), XbbRefTypeEnum.PUSH_NOTIFY.getCode())));
        return singleDataMessageGetVO;
    }

    @Override
    public PhoneForDialGetVO getPhoneForDial(PhoneForDialGetDTO phoneForDialGetDTO) throws XbbException {
        Long dataId = phoneForDialGetDTO.getDataId();
        String corpid = phoneForDialGetDTO.getCorpid();
        Integer businessType = phoneForDialGetDTO.getBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
        WorkOrderEntity workOrderEntity = new WorkOrderEntity();
        JSONObject data;
        PhoneForDialGetVO phoneForDialGetVO = new PhoneForDialGetVO();
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            workOrderEntity = workOrderModel.getByKey(dataId, corpid);
            if (Objects.isNull(workOrderEntity) || Objects.equals(workOrderEntity.getDel(), DelEnum.DELETE.getDel())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            data = workOrderEntity.getData();
        } else {
            paasFormDataEntityExt = proGetHelp.getByKey(dataId, businessType, phoneForDialGetDTO.getSaasMark(), corpid);
            if (Objects.isNull(paasFormDataEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            data = paasFormDataEntityExt.getData();
        }
        FieldAttrEntity fieldAttrEntity = null;
        Map<String, FieldAttrEntity> explainMap = null;
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(phoneForDialGetDTO,handlerExplainDTO);
        PaasFormExplainEntity paasFormExplainEntity = null;
        String explains = null;
        // 根据distributorMark判断是：客户/经销商客户、联系人/经销商联系人....
        Integer distributorMark = DistributorMarkEnum.OTHER.getCode();
        if(Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())){
            Long templateId = workOrderEntity.getTemplateId();
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByTemplateId(templateId, corpid);
            if(Objects.nonNull(workOrderFormEntityExt)){
                WorkOrderExplainEntityExt  workOrderExplainEntityExt  = workOrderExplainModel.getByFormId(workOrderFormEntityExt.getId(), corpid);
                if(Objects.nonNull(workOrderExplainEntityExt)) {
                    explains = workOrderExplainEntityExt.getExplains();
                }
            }
        } else {
            paasFormExplainEntity = paasFormExplainModel.getByFormId(paasFormDataEntityExt.getFormId(),corpid);
            distributorMark = paasFormExplainEntity.getDistributorMark();
            if(Objects.nonNull(paasFormExplainEntity) && Objects.equals(paasFormExplainEntity.getDel(), DelEnum.NORMAL.getDel())) {
                explains = paasFormExplainEntity.getExplains();
            }
        }
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(Objects.nonNull(explains)){
            explainMap = ExplainUtil.getExplainMap(explains, null);
            List<FieldAttrEntity> explainList = JSONArray.parseArray(explains, FieldAttrEntity.class);
            handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(phoneForDialGetDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            userMap = userAndDepartmentGetVO.getUserMap();
            handlerExplainDTO.setExplainList(explainList);
            // 获取协同人和负责人
            paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, phoneForDialGetDTO.getSaasMark(), businessType,null, paasFormDataEntityExt, userMap);
        } else {
            handlerExplainDTO.setExplainList(new ArrayList<>());
        }

        List<MobileDetailDialPhonePojo> mainPhoneList = new ArrayList<>();
        List<MobileDetailDialPhonePojo> contactPhoneList = new ArrayList<>();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        Boolean isOpen = false;
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                Boolean publicCanSeePhone = true;
                Boolean customerNameVisiable = false;
                Integer publicCustomer = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);

                JSONArray customerPhoneArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerManagementEnum.PHONE.getAttr(), new JSONArray());
                String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
                if(explainMap!=null){
                    fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                    if (Objects.equals(publicCustomer, BasicConstant.ONE) && Objects.nonNull(fieldAttrEntity)) {
                        Integer showPublicPool = fieldAttrEntity.getShowPublicPool();
                        Integer publicPool = fieldAttrEntity.getPublicPool();
                        if (Objects.equals(showPublicPool, BasicConstant.ONE) && Objects.equals(publicPool, BasicConstant.ZERO)) {
                            publicCanSeePhone = false;
                        }
                    }

                    FieldAttrEntity nameAttrEntity = explainMap.get(CustomerManagementEnum.NAME.getAttr());
                    if (Objects.nonNull(nameAttrEntity)) {
                        customerNameVisiable = !ExplainUtil.fieldAttrHide(nameAttrEntity, handlerExplainDTO);
                    }
                }
                // 判断子表单是否启用
                if(Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ONE) && Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ONE)){
                    isOpen = true;
                }
                //获取子表单里的手机字段
                fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                if(isOpen){
                    mainPhoneList = commonHelp.handlePhoneForDetail(publicCanSeePhone, customerPhoneArr, customerName, RedundantTemplateTypeEnum.CUSTOMER.getCode(), paasFormDataEntityExt.getId(),handlerExplainDTO,fieldAttrEntity, customerNameVisiable);
                }
                if (!publicCanSeePhone) {
                    phoneForDialGetVO.setMainPhoneNoCall(BasicConstant.ONE);
                }

                // 联系人电话
                Boolean publicContactPhone = true;
                Boolean contactNameVisiable = false;
                PaasFormExplainEntity contactExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTACT.getCode(), corpid);
                Map<String, FieldAttrEntity> contactAttrEntity = ExplainUtil.getExplainMap(contactExplain.getExplains());
                FieldAttrEntity contactPhoneAttr = contactAttrEntity.get(ContactEnum.PHONE.getAttr());
                FieldAttrEntity contactnameAttr = contactAttrEntity.get(ContactEnum.NAME.getAttr());
                Boolean contactSerialNoSee = false;
                FieldAttrEntity contactSerialNoField = contactAttrEntity.get(BasicConstant.SERIAL_NO);
                if (Objects.nonNull(contactSerialNoField)) {
                    contactSerialNoSee = !ExplainUtil.fieldAttrHide(contactSerialNoField, handlerExplainDTO);
                }
                Boolean contactDepartMentSee = false;
                FieldAttrEntity contactDepartMentField = contactAttrEntity.get("departmentId");
                if (Objects.nonNull(contactDepartMentField)) {
                    contactDepartMentSee = !ExplainUtil.fieldAttrHide(contactDepartMentField, handlerExplainDTO);
                }
                Boolean contactCustomerNameSee = false;
                FieldAttrEntity contactCustomerNameField = contactAttrEntity.get(ContactEnum.CUSTOMER_NAME.getAttr());
                if (Objects.nonNull(contactCustomerNameField)) {
                    contactCustomerNameSee = !ExplainUtil.fieldAttrHide(contactCustomerNameField, handlerExplainDTO);
                }
                Boolean contactEmailSee = false;
                FieldAttrEntity contactEmailField = contactAttrEntity.get(ContactEnum.EMAIL.getAttr());
                if (Objects.nonNull(contactEmailField)) {
                    contactEmailSee = !ExplainUtil.fieldAttrHide(contactEmailField, handlerExplainDTO);
                }
                Boolean contactQQSee = false;
                FieldAttrEntity contactQQField = contactAttrEntity.get(ContactEnum.QQ.getAttr());
                if (Objects.nonNull(contactQQField)) {
                    contactQQSee = !ExplainUtil.fieldAttrHide(contactQQField, handlerExplainDTO);
                }
                Boolean contactZipCodeSee = false;
                FieldAttrEntity contactZipCodeField = contactAttrEntity.get(ContactEnum.ZIP_CODE.getAttr());
                if (Objects.nonNull(contactZipCodeField)) {
                    contactZipCodeSee = !ExplainUtil.fieldAttrHide(contactZipCodeField, handlerExplainDTO);
                }
                Boolean contactSexSee = false;
                FieldAttrEntity contactSexField = contactAttrEntity.get(ContactEnum.SEX.getAttr());
                if (Objects.nonNull(contactSexField)) {
                    contactSexSee = !ExplainUtil.fieldAttrHide(contactSexField, handlerExplainDTO);
                }
                Boolean contactHobbiesSee = false;
                FieldAttrEntity contactHobbiesField = contactAttrEntity.get(ContactEnum.HOBBIES.getAttr());
                if (Objects.nonNull(contactHobbiesField)) {
                    contactHobbiesSee = !ExplainUtil.fieldAttrHide(contactHobbiesField, handlerExplainDTO);
                }
                Boolean contactDepartSee = false;
                FieldAttrEntity contactDepartField = contactAttrEntity.get(ContactEnum.DEPARTMENT.getAttr());
                if (Objects.nonNull(contactDepartField)) {
                    contactDepartSee = !ExplainUtil.fieldAttrHide(contactDepartField, handlerExplainDTO);
                }
                Boolean contactPositionSee = false;
                FieldAttrEntity contactPositionField = contactAttrEntity.get(ContactEnum.POSITION.getAttr());
                if (Objects.nonNull(contactPositionField)) {
                    contactPositionSee = !ExplainUtil.fieldAttrHide(contactPositionField, handlerExplainDTO);
                }
                Boolean contactLevelSee = false;
                FieldAttrEntity contactLevelField = contactAttrEntity.get(ContactEnum.LEVEL.getAttr());
                if (Objects.nonNull(contactLevelField)) {
                    contactLevelSee = !ExplainUtil.fieldAttrHide(contactLevelField, handlerExplainDTO);
                }
                Boolean contactImportDegreeSee = false;
                FieldAttrEntity contactImportDegreeField = contactAttrEntity.get(ContactEnum.IMPORTANT_DEGREE.getAttr());
                if (Objects.nonNull(contactImportDegreeField)) {
                    contactImportDegreeSee = !ExplainUtil.fieldAttrHide(contactImportDegreeField, handlerExplainDTO);
                }
                Boolean contactRelationshipSee = false;
                FieldAttrEntity contactRelationshipField = contactAttrEntity.get(ContactEnum.RELATIONSHIP.getAttr());
                if (Objects.nonNull(contactRelationshipField)) {
                    contactRelationshipSee = !ExplainUtil.fieldAttrHide(contactRelationshipField, handlerExplainDTO);
                }
                Boolean contactIntimateDegreeSee = false;
                FieldAttrEntity contactIntimateDegreeField = contactAttrEntity.get(ContactEnum.INTIMATE_DEGREE.getAttr());
                if (Objects.nonNull(contactIntimateDegreeField)) {
                    contactIntimateDegreeSee = !ExplainUtil.fieldAttrHide(contactIntimateDegreeField, handlerExplainDTO);
                }
                Boolean contactCreatorIdSee = false;
                FieldAttrEntity contactCreatorIdField = contactAttrEntity.get(ContactEnum.CREATOR_ID.getAttr());
                if (Objects.nonNull(contactCreatorIdField)) {
                    contactCreatorIdSee = !ExplainUtil.fieldAttrHide(contactCreatorIdField, handlerExplainDTO);
                }
                Boolean contactAddTimeSee = false;
                FieldAttrEntity contactAddTimeField = contactAttrEntity.get(ContactEnum.ADD_TIME.getAttr());
                if (Objects.nonNull(contactAddTimeField)) {
                    contactAddTimeSee = !ExplainUtil.fieldAttrHide(contactAddTimeField, handlerExplainDTO);
                }
                Boolean contactUpdateTimeSee = false;
                FieldAttrEntity contactUpdateTimeField = contactAttrEntity.get(ContactEnum.UPDATE_TIME.getAttr());
                if (Objects.nonNull(contactUpdateTimeField)) {
                    contactUpdateTimeSee = !ExplainUtil.fieldAttrHide(contactUpdateTimeField, handlerExplainDTO);
                }

                if (Objects.equals(publicCustomer, BasicConstant.ONE) && Objects.nonNull(contactPhoneAttr)) {
                    Integer showPublicPool = contactPhoneAttr.getShowPublicPool();
                    Integer publicPool = contactPhoneAttr.getPublicPool();
                    if (Objects.equals(showPublicPool, BasicConstant.ONE) && Objects.equals(publicPool, BasicConstant.ZERO)) {
                        publicContactPhone = false;
                    }
                }
                IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_SAAS_CONTACT;
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME), paasFormDataEntityExt.getId()));
                boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
                //加上团队权限过滤
                if (Objects.equals(DistributorMarkEnum.OTHER.getCode(), phoneForDialGetDTO.getDistributorMark())) {
                    List<String> userIds = detailTabDataPermissionHelp.detailTeamBoolQueryParamPermission(boolQueryBuilder, phoneForDialGetDTO.getCorpid(), phoneForDialGetDTO.getFormId(),
                            phoneForDialGetDTO.getBusinessType(), XbbRefTypeEnum.CONTACT.getCode(), phoneForDialGetDTO.getLoginUser(), IndexTypeEnum.IDX_SAAS_CONTACT_TEAM);
                    PaasFormEntityExt formEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.CONTACT.getCode(), corpid);
                    // 共享权限处理
                    saasListDataPermissionHelp.parseSharePermissionBoolQueryForUserId(boolQueryBuilder, Collections.singletonList(formEntityExt.getId()), userIds, phoneForDialGetDTO.getLoginUser(), XbbRefTypeEnum.CONTACT.getCode());

                }
                sourceBuilder.query(boolQueryBuilder);
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, EsNormalConstant.FIND_NUM);
                SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
                searchRequest.source(sourceBuilder);
                XbbAggregatedPage<PaasFormDataEntityExt> paasFormDataEntityExts = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);

                // 跳转穿透
                Map<Long, DataDetailTabPojo> detailTabPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                // 标签
                Map<Long, JSONArray> detailTagMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                UserVO loginUser = phoneForDialGetDTO.getLoginUser();
                boolean isNeedContact = (loginUser.isAdminOrBoss() || loginUser.getPermSet().contains(ProPermissionAliasEnum.CONTACT_VIEW.getAlias()));
                for (PaasFormDataEntityExt contactEntity : paasFormDataEntityExts.getContent()) {
                    Long contactId = contactEntity.getId();
                    JSONObject dataList = contactEntity.getData();
                    handlerExplainDTO.setCreatorId(contactEntity.getCreatorId());
                    // 获取协同人和负责人
                    paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, phoneForDialGetDTO.getSaasMark(), XbbRefTypeEnum.CONTACT.getCode(),null, contactEntity, userMap);
                    if (Objects.nonNull(contactnameAttr)) {
                        contactNameVisiable = !ExplainUtil.fieldAttrHide(contactnameAttr, handlerExplainDTO);
                    }

                    JSONArray contactPhoneArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, ContactEnum.PHONE.getAttr(), new JSONArray());
                    String contactName = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ContactEnum.NAME.getAttr(), "");
                    //联系人的电话可见权限由联系人模板控制
                    fieldAttrEntity = commonHelp.getSubFormAttr(contactPhoneAttr);
                    if(isNeedContact){
                        contactPhoneList.addAll(commonHelp.handlePhoneForDetail(publicContactPhone, contactPhoneArr, contactName, RedundantTemplateTypeEnum.CONTACT.getCode(), contactId,handlerExplainDTO,fieldAttrEntity, contactNameVisiable));
                    }
                    // 获取关联的联系人的表单id
                    Long contactForm = contactEntity.getFormId();
                    //跳转需要的参数
                    DataDetailTabPojo dataDetailTabPojo = new DataDetailTabPojo();
                    dataDetailTabPojo.setAppId(contactEntity.getAppId());
                    dataDetailTabPojo.setDataId(contactId);
                    dataDetailTabPojo.setMenuId(contactEntity.getMenuId());
                    dataDetailTabPojo.setFormId(contactForm);
                    dataDetailTabPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    dataDetailTabPojo.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
                    dataDetailTabPojo.setDistributorMark(phoneForDialGetDTO.getDistributorMark());
                    detailTabPojoMap.put(contactId, dataDetailTabPojo);

                    if(!Objects.equals(contactForm, 0L)){
                        // 获取联系人表单字段解释
                        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(contactForm, corpid);
                        // 获取联系人关联的数据标签
                        List<SummaryDataPoJo> labels = JSONArray.parseArray(paasFormEntityExt.getLabels(), SummaryDataPoJo.class);
                        labels = labels == null ? new ArrayList<>() : labels;
                        // 标签
                        // 字段高级可见
                        Map<String, Boolean> contactVisiableMap = new HashMap<>();
                        contactVisiableMap.put(ContactEnum.NAME.getAttr(), contactNameVisiable);
                        contactVisiableMap.put(BasicConstant.SERIAL_NO, contactSerialNoSee);
                        contactVisiableMap.put("departmentId", contactDepartMentSee);
                        contactVisiableMap.put(ContactEnum.CUSTOMER_NAME.getAttr(), contactCustomerNameSee);
                        contactVisiableMap.put(ContactEnum.EMAIL.getAttr(), contactEmailSee);
                        contactVisiableMap.put(ContactEnum.QQ.getAttr(),  contactQQSee);
                        contactVisiableMap.put(ContactEnum.ZIP_CODE.getAttr(), contactZipCodeSee);
                        contactVisiableMap.put(ContactEnum.SEX.getAttr(), contactSexSee);
                        contactVisiableMap.put(ContactEnum.HOBBIES.getAttr(), contactHobbiesSee);
                        contactVisiableMap.put(ContactEnum.DEPARTMENT.getAttr(), contactDepartSee);
                        contactVisiableMap.put(ContactEnum.POSITION.getAttr(), contactPositionSee);
                        contactVisiableMap.put(ContactEnum.LEVEL.getAttr(), contactLevelSee);
                        contactVisiableMap.put(ContactEnum.IMPORTANT_DEGREE.getAttr(), contactImportDegreeSee);
                        contactVisiableMap.put(ContactEnum.RELATIONSHIP.getAttr(), contactRelationshipSee);
                        contactVisiableMap.put(ContactEnum.INTIMATE_DEGREE.getAttr(), contactIntimateDegreeSee);
                        contactVisiableMap.put(ContactEnum.CREATOR_ID.getAttr(), contactCreatorIdSee);
                        contactVisiableMap.put(ContactEnum.ADD_TIME.getAttr(), contactAddTimeSee);
                        contactVisiableMap.put(ContactEnum.UPDATE_TIME.getAttr(), contactUpdateTimeSee);

                        JSONArray tags = handleMobileTag(contactEntity, paasFormDataEntityExt.getSerialNo(), paasFormDataEntityExt.getDepartmentId(), labels, dataList, contactAttrEntity, contactVisiableMap, redundantTemplateTypeEnum);

                        detailTagMap.put(contactId, tags);
                    }
                }

                contactPhoneList.forEach(item -> {
                    Long contactId = item.getDataId();
                    if(detailTabPojoMap.containsKey(contactId)){
                        item.setEntity(detailTabPojoMap.get(contactId));
                    }
                    if(detailTagMap.containsKey(contactId)){
                        item.setTags(detailTagMap.get(contactId));
                    }
                });

                if (!publicContactPhone) {
                    phoneForDialGetVO.setContactPhoneNoCall(BasicConstant.ONE);
                }
                break;
            case CONTACT:
                Boolean contactPhoneSee = true;
                Boolean contactNameSee = false;
                Boolean serialNoSee = false;
                Boolean departMentSee = false;
                Boolean customerNameSee = false;
                Boolean emailSee = false;
                Boolean qQSee = false;
                Boolean zipCodeSee = false;
                Boolean sexSee = false;
                Boolean hobbiesSee = false;
                Boolean departSee = false;
                Boolean positionSee = false;
                Boolean levelSee = false;
                Boolean importDegreeSee = false;
                Boolean relationshipSee = false;
                Boolean intimateDegreeSee = false;
                Boolean creatorIdSee = false;
                Boolean addTimeSee = false;
                Boolean updateTimeSee = false;

                JSONArray contactPhoneArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ContactEnum.PHONE.getAttr(), new JSONArray());
                String contactName = FastJsonHelper.getStringOrDefaultFromFormData(data, ContactEnum.NAME.getAttr(), "");
                if(explainMap!=null) {
                    fieldAttrEntity = explainMap.get(ContactEnum.PHONE.getAttr());
                    Long contactCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(data, ContactEnum.CUSTOMER_NAME.getAttr(), 0L);
                    // 联系人可以不关联客户
                    if (Objects.equals(DistributorMarkEnum.OTHER.getCode(), distributorMark) && Objects.equals(BasicConstant.ZERO_LONG, contactCustomerId)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.LINK_CUSTOMER);
                    }
                    PaasFormDataEntityExt customerEntity = proGetHelp.getByKey(contactCustomerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
                    if (Objects.isNull(customerEntity)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                    }
                    Integer contactCustomerPublic = getIntegerOrDefaultFromFormData(customerEntity.getData(), CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);

                    if (Objects.equals(contactCustomerPublic, BasicConstant.ONE) && Objects.nonNull(fieldAttrEntity)) {
                        Integer showPublicPool = fieldAttrEntity.getShowPublicPool();
                        Integer publicPool = fieldAttrEntity.getPublicPool();
                        if (Objects.equals(showPublicPool, BasicConstant.ONE) && Objects.equals(publicPool, BasicConstant.ZERO)) {
                            contactPhoneSee = false;
                        }
                    }
                    FieldAttrEntity contactNameField = explainMap.get(ContactEnum.NAME.getAttr());
                    if (Objects.nonNull(contactNameField)) {
                        contactNameSee = !ExplainUtil.fieldAttrHide(contactNameField, handlerExplainDTO);
                    }
                    FieldAttrEntity serialNoField = explainMap.get(BasicConstant.SERIAL_NO);
                    if (Objects.nonNull(serialNoField)) {
                        serialNoSee = !ExplainUtil.fieldAttrHide(serialNoField, handlerExplainDTO);
                    }
                    FieldAttrEntity departMentField = explainMap.get("departmentId");
                    if (Objects.nonNull(departMentField)) {
                        departMentSee = !ExplainUtil.fieldAttrHide(departMentField, handlerExplainDTO);
                    }
                    FieldAttrEntity customerNameField = explainMap.get(ContactEnum.CUSTOMER_NAME.getAttr());
                    if (Objects.nonNull(customerNameField)) {
                        customerNameSee = !ExplainUtil.fieldAttrHide(customerNameField, handlerExplainDTO);
                    }
                    FieldAttrEntity emailField = explainMap.get(ContactEnum.EMAIL.getAttr());
                    if (Objects.nonNull(emailField)) {
                        emailSee = !ExplainUtil.fieldAttrHide(emailField, handlerExplainDTO);
                    }
                    FieldAttrEntity qQField = explainMap.get(ContactEnum.QQ.getAttr());
                    if (Objects.nonNull(qQField)) {
                        qQSee = !ExplainUtil.fieldAttrHide(qQField, handlerExplainDTO);
                    }
                    FieldAttrEntity zipCodeField = explainMap.get(ContactEnum.ZIP_CODE.getAttr());
                    if (Objects.nonNull(zipCodeField)) {
                        zipCodeSee = !ExplainUtil.fieldAttrHide(zipCodeField, handlerExplainDTO);
                    }
                    FieldAttrEntity sexField = explainMap.get(ContactEnum.SEX.getAttr());
                    if (Objects.nonNull(sexField)) {
                        sexSee = !ExplainUtil.fieldAttrHide(sexField, handlerExplainDTO);
                    }
                    FieldAttrEntity hobbiesField = explainMap.get(ContactEnum.HOBBIES.getAttr());
                    if (Objects.nonNull(hobbiesField)) {
                        hobbiesSee = !ExplainUtil.fieldAttrHide(hobbiesField, handlerExplainDTO);
                    }
                    FieldAttrEntity departField = explainMap.get(ContactEnum.DEPARTMENT.getAttr());
                    if (Objects.nonNull(departField)) {
                        departSee = !ExplainUtil.fieldAttrHide(departField, handlerExplainDTO);
                    }
                    FieldAttrEntity positionField = explainMap.get(ContactEnum.POSITION.getAttr());
                    if (Objects.nonNull(positionField)) {
                        positionSee = !ExplainUtil.fieldAttrHide(positionField, handlerExplainDTO);
                    }
                    FieldAttrEntity levelField = explainMap.get(ContactEnum.LEVEL.getAttr());
                    if (Objects.nonNull(levelField)) {
                        levelSee = !ExplainUtil.fieldAttrHide(levelField, handlerExplainDTO);
                    }
                    FieldAttrEntity importDegreeField = explainMap.get(ContactEnum.IMPORTANT_DEGREE.getAttr());
                    if (Objects.nonNull(importDegreeField)) {
                        importDegreeSee = !ExplainUtil.fieldAttrHide(importDegreeField, handlerExplainDTO);
                    }
                    FieldAttrEntity relationshipField = explainMap.get(ContactEnum.RELATIONSHIP.getAttr());
                    if (Objects.nonNull(relationshipField)) {
                        relationshipSee = !ExplainUtil.fieldAttrHide(relationshipField, handlerExplainDTO);
                    }
                    FieldAttrEntity intimateDegreeField = explainMap.get(ContactEnum.INTIMATE_DEGREE.getAttr());
                    if (Objects.nonNull(intimateDegreeField)) {
                        intimateDegreeSee = !ExplainUtil.fieldAttrHide(intimateDegreeField, handlerExplainDTO);
                    }
                    FieldAttrEntity creatorIdField = explainMap.get(ContactEnum.CREATOR_ID.getAttr());
                    if (Objects.nonNull(creatorIdField)) {
                        creatorIdSee = !ExplainUtil.fieldAttrHide(creatorIdField, handlerExplainDTO);
                    }
                    FieldAttrEntity addTimeField = explainMap.get(ContactEnum.ADD_TIME.getAttr());
                    if (Objects.nonNull(addTimeField)) {
                        addTimeSee = !ExplainUtil.fieldAttrHide(addTimeField, handlerExplainDTO);
                    }
                    FieldAttrEntity updateTimeField = explainMap.get(ContactEnum.UPDATE_TIME.getAttr());
                    if (Objects.nonNull(updateTimeField)) {
                        updateTimeSee = !ExplainUtil.fieldAttrHide(updateTimeField, handlerExplainDTO);
                    }
                }
                //获取子表单里的手机字段
                fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                contactPhoneList.addAll(commonHelp.handlePhoneForDetail(contactPhoneSee, contactPhoneArr, contactName, RedundantTemplateTypeEnum.CONTACT.getCode(), paasFormDataEntityExt.getId(),handlerExplainDTO,fieldAttrEntity, contactNameSee));

                // 标签
                Map<Long, JSONArray> contactTagMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Long contactForm = paasFormDataEntityExt.getFormId();
                if(!Objects.equals(contactForm, 0L)){
                    // 获取联系人表单字段解释
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(contactForm, corpid);
                    // 获取联系人关联的数据标签
                    List<SummaryDataPoJo> labels = JSONArray.parseArray(paasFormEntityExt.getLabels(), SummaryDataPoJo.class);
                    labels = labels == null ? new ArrayList<>() : labels;
                    // 标签
                    // 字段高级可见
                    Map<String, Boolean> contactVisiableMap = new HashMap<>();
                    contactVisiableMap.put(ContactEnum.NAME.getAttr(), contactNameSee);
                    contactVisiableMap.put(BasicConstant.SERIAL_NO, serialNoSee);
                    contactVisiableMap.put("departmentId", departMentSee);
                    contactVisiableMap.put(ContactEnum.CUSTOMER_NAME.getAttr(), customerNameSee);
                    contactVisiableMap.put(ContactEnum.EMAIL.getAttr(), emailSee);
                    contactVisiableMap.put(ContactEnum.QQ.getAttr(),  qQSee);
                    contactVisiableMap.put(ContactEnum.ZIP_CODE.getAttr(), zipCodeSee);
                    contactVisiableMap.put(ContactEnum.SEX.getAttr(), sexSee);
                    contactVisiableMap.put(ContactEnum.HOBBIES.getAttr(), hobbiesSee);
                    contactVisiableMap.put(ContactEnum.DEPARTMENT.getAttr(), departSee);
                    contactVisiableMap.put(ContactEnum.POSITION.getAttr(), positionSee);
                    contactVisiableMap.put(ContactEnum.LEVEL.getAttr(), levelSee);
                    contactVisiableMap.put(ContactEnum.IMPORTANT_DEGREE.getAttr(), importDegreeSee);
                    contactVisiableMap.put(ContactEnum.RELATIONSHIP.getAttr(), relationshipSee);
                    contactVisiableMap.put(ContactEnum.INTIMATE_DEGREE.getAttr(), intimateDegreeSee);
                    contactVisiableMap.put(ContactEnum.CREATOR_ID.getAttr(), creatorIdSee);
                    contactVisiableMap.put(ContactEnum.ADD_TIME.getAttr(), addTimeSee);
                    contactVisiableMap.put(ContactEnum.UPDATE_TIME.getAttr(), updateTimeSee);
                    JSONArray tags = handleMobileTag(paasFormDataEntityExt, paasFormDataEntityExt.getSerialNo(), paasFormDataEntityExt.getDepartmentId(), labels, data, explainMap, contactVisiableMap, redundantTemplateTypeEnum);
                    contactTagMap.put(paasFormDataEntityExt.getId(), tags);
                }
                contactPhoneList.forEach(item -> {
                    Long contactId = item.getDataId();
                    if(contactTagMap.containsKey(contactId)){
                        item.setTags(contactTagMap.get(contactId));
                    }
                });

                if (!contactPhoneSee) {
                    phoneForDialGetVO.setContactPhoneNoCall(BasicConstant.ONE);
                }
                break;
            case SUPPLIER:
                JSONArray supplierPhoneArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, SupplierEnum.PHONE.getAttr(), new JSONArray());
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                if(explainMap!=null) {
                    fieldAttrEntity = explainMap.get(SupplierEnum.PHONE.getAttr());
                }
                // 判断子表单是否启用
                if(Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ONE) && Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ONE)){
                    isOpen = true;
                }
                //获取子表单里的手机字段
                fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                if(isOpen){
                    mainPhoneList.addAll(handleDialPhone(supplierPhoneArr, supplierName, RedundantTemplateTypeEnum.SUPPLIER.getCode(), paasFormDataEntityExt.getId(),handlerExplainDTO,fieldAttrEntity, handlerExplainDTO.getLoginUser()));
                }
                Map<String, Object> supplierParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                supplierParam.put(ParameterConstant.CORPID, corpid);
                supplierParam.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                supplierParam.put(ParameterConstant.FLOW_STATUS_IN, Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType()));
                List<PaasFormDataEntityExt> supplierContactList = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.SUPPLIER_CONTACT.getCode(), SupplierContactEnum.SUPPLIER_ID.getAttr(), paasFormDataEntityExt.getId(), supplierParam, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
                Map<String, FieldAttrEntity> supplierContractExplainMap = saasListHelp.getExplains(RedundantTemplateTypeEnum.SUPPLIER_CONTACT.getCode(),corpid);
                Boolean supplierContactNameSee = false;
                Boolean supplierContactSerialNoSee = false;
                Boolean supplierContactDepartMentSee = false;
                Boolean supplierNameSee = false;
                Boolean supplierCreatSee = false;
                Boolean supplierAddTimeSee = false;
                Boolean supplierUpdateTimeSee = false;
                Boolean supplierEmailSee = false;
                Boolean supplierQQSee = false;
                Boolean supplierSexSee = false;
                Boolean supplierPositionSee = false;
                Boolean supplierLevelSee = false;

                FieldAttrEntity contactNameField = supplierContractExplainMap.get(SupplierContactEnum.NAME.getAttr());
                if (Objects.nonNull(contactNameField)) {
                    supplierContactNameSee = !ExplainUtil.fieldAttrHide(contactNameField, handlerExplainDTO);
                }
                FieldAttrEntity serialNoField = supplierContractExplainMap.get(BasicConstant.SERIAL_NO);
                if (Objects.nonNull(serialNoField)) {
                    supplierContactSerialNoSee = !ExplainUtil.fieldAttrHide(serialNoField, handlerExplainDTO);
                }
                FieldAttrEntity departMentField = supplierContractExplainMap.get(SupplierContactEnum.DEPARTMENT.getAttr());
                if (Objects.nonNull(departMentField)) {
                    supplierContactDepartMentSee = !ExplainUtil.fieldAttrHide(departMentField, handlerExplainDTO);
                }
                FieldAttrEntity supplierNameField = supplierContractExplainMap.get(SupplierContactEnum.SUPPLIER_ID.getAttr());
                if (Objects.nonNull(supplierNameField)) {
                    supplierNameSee = !ExplainUtil.fieldAttrHide(supplierNameField, handlerExplainDTO);
                }
                FieldAttrEntity supplierCreatField = supplierContractExplainMap.get(StringConstant.CREATOR_ID);
                if (Objects.nonNull(supplierCreatField)) {
                    supplierCreatSee = !ExplainUtil.fieldAttrHide(supplierCreatField, handlerExplainDTO);
                }
                FieldAttrEntity supplierAddTimeField = supplierContractExplainMap.get(StringConstant.ADD_TIME);
                if (Objects.nonNull(supplierAddTimeField)) {
                    supplierAddTimeSee = !ExplainUtil.fieldAttrHide(supplierAddTimeField, handlerExplainDTO);
                }
                FieldAttrEntity supplierUpdateTimeField = supplierContractExplainMap.get(StringConstant.UPDATE_TIME);
                if (Objects.nonNull(supplierUpdateTimeField)) {
                    supplierUpdateTimeSee = !ExplainUtil.fieldAttrHide(supplierUpdateTimeField, handlerExplainDTO);
                }
                FieldAttrEntity supplierEmailField = supplierContractExplainMap.get(SupplierContactEnum.EMAIL.getAttr());
                if (Objects.nonNull(supplierEmailField)) {
                    supplierEmailSee = !ExplainUtil.fieldAttrHide(supplierEmailField, handlerExplainDTO);
                }
                FieldAttrEntity supplierQQField = supplierContractExplainMap.get(SupplierContactEnum.QQ.getAttr());
                if (Objects.nonNull(supplierQQField)) {
                    supplierQQSee = !ExplainUtil.fieldAttrHide(supplierQQField, handlerExplainDTO);
                }
                FieldAttrEntity supplierSexField = supplierContractExplainMap.get(SupplierContactEnum.SEX.getAttr());
                if (Objects.nonNull(supplierSexField)) {
                    supplierSexSee = !ExplainUtil.fieldAttrHide(supplierSexField, handlerExplainDTO);
                }
                FieldAttrEntity supplierPositionField = supplierContractExplainMap.get(SupplierContactEnum.POSITION.getAttr());
                if (Objects.nonNull(supplierPositionField)) {
                    supplierPositionSee = !ExplainUtil.fieldAttrHide(supplierPositionField, handlerExplainDTO);
                }
                FieldAttrEntity supplierLevelField = supplierContractExplainMap.get(SupplierContactEnum.LEVEL.getAttr());
                if (Objects.nonNull(supplierLevelField)) {
                    supplierLevelSee = !ExplainUtil.fieldAttrHide(supplierLevelField, handlerExplainDTO);
                }
                // 跳转穿透
                Map<Long, DataDetailTabPojo> supplierTabPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                // 标签
                Map<Long, JSONArray> supplierTagMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormDataEntityExt supplierContactEntity : supplierContactList) {
                    Long supplierContactId = supplierContactEntity.getId();
                    JSONObject supplierContactData = supplierContactEntity.getData();
                    if(!supplierContactNameSee){
                        supplierContactData.remove(SupplierContactEnum.NAME.getAttr());
                    }
                    JSONArray supplierContactPhoneArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(supplierContactData, SupplierContactEnum.PHONE.getAttr(), new JSONArray());
                    String supplierContactName = FastJsonHelper.getStringOrDefaultFromFormData(supplierContactData, SupplierContactEnum.NAME.getAttr(), "");
                    if(supplierContractExplainMap!=null) {
                        fieldAttrEntity = supplierContractExplainMap.get(SupplierContactEnum.PHONE.getAttr());
                    }
                    //获取子表单里的手机字段
                    fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                    contactPhoneList.addAll(handleDialPhone(supplierContactPhoneArr, supplierContactName, RedundantTemplateTypeEnum.SUPPLIER_CONTACT.getCode(), supplierContactId,handlerExplainDTO,fieldAttrEntity, handlerExplainDTO.getLoginUser()));

                    // 获取关联的联系人的表单id
                    Long supplierContactFormId = supplierContactEntity.getFormId();
                    //跳转需要的参数
                    DataDetailTabPojo dataDetailTabPojo = new DataDetailTabPojo();
                    dataDetailTabPojo.setAppId(supplierContactEntity.getAppId());
                    dataDetailTabPojo.setDataId(supplierContactId);
                    dataDetailTabPojo.setMenuId(supplierContactEntity.getMenuId());
                    dataDetailTabPojo.setFormId(supplierContactFormId);
                    dataDetailTabPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    dataDetailTabPojo.setBusinessType(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode());
                    supplierTabPojoMap.put(supplierContactId, dataDetailTabPojo);

                    if(!Objects.equals(supplierContactFormId, 0L)){
                        // 获取联系人表单字段解释
                        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(supplierContactFormId, corpid);
                        // 获取联系人关联的数据标签
                        List<SummaryDataPoJo> labels = JSONArray.parseArray(paasFormEntityExt.getLabels(), SummaryDataPoJo.class);
                        labels = labels == null ? new ArrayList<>() : labels;
                        // 标签
                        // 字段高级可见
                        Map<String, Boolean> contactVisiableMap = new HashMap<>();
                        contactVisiableMap.put(SupplierContactEnum.NAME.getAttr(), supplierContactNameSee);
                        contactVisiableMap.put(BasicConstant.SERIAL_NO, supplierContactSerialNoSee);
                        contactVisiableMap.put(SupplierContactEnum.DEPARTMENT.getAttr(), supplierContactDepartMentSee);
                        contactVisiableMap.put(SupplierContactEnum.SUPPLIER_ID.getAttr(), supplierNameSee);
                        contactVisiableMap.put(StringConstant.CREATOR_ID,  supplierCreatSee);
                        contactVisiableMap.put(StringConstant.ADD_TIME, supplierAddTimeSee);
                        contactVisiableMap.put(StringConstant.UPDATE_TIME, supplierUpdateTimeSee);
                        contactVisiableMap.put(SupplierContactEnum.EMAIL.getAttr(), supplierEmailSee);
                        contactVisiableMap.put(SupplierContactEnum.QQ.getAttr(), supplierQQSee);
                        contactVisiableMap.put(SupplierContactEnum.SEX.getAttr(), supplierSexSee);
                        contactVisiableMap.put(SupplierContactEnum.POSITION.getAttr(), supplierPositionSee);
                        contactVisiableMap.put(ContactEnum.LEVEL.getAttr(), supplierLevelSee);
                        JSONArray tags = handleMobileTag(supplierContactEntity, supplierContactEntity.getSerialNo(),supplierContactEntity.getDepartmentId(), labels, supplierContactData, supplierContractExplainMap, contactVisiableMap, redundantTemplateTypeEnum);
                        supplierTagMap.put(supplierContactId, tags);
                    }
                }
                contactPhoneList.forEach(item -> {
                    Long contactId = item.getDataId();
                    if(supplierTabPojoMap.containsKey(contactId)){
                        item.setEntity(supplierTabPojoMap.get(contactId));
                    }
                    if(supplierTagMap.containsKey(contactId)){
                        item.setTags(supplierTagMap.get(contactId));
                    }
                });

                break;
            case WORKORDER:
                JSONArray workOrderPhoneArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, WorkOrderEnum.CONTACT_INFORMATION.getAttr(), new JSONArray());
                if(explainMap!=null) {
                    fieldAttrEntity = explainMap.get(WorkOrderEnum.CONTACT_INFORMATION.getAttr());
                }
                //获取子表单里的手机字段
                fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                contactPhoneList.addAll(handleDialPhone(workOrderPhoneArr, null, RedundantTemplateTypeEnum.WORKORDER.getCode(), workOrderEntity.getId(),handlerExplainDTO,fieldAttrEntity, handlerExplainDTO.getLoginUser()));
                break;
            case COMMUNICATE_PLAN:
            case PAYMENT_TASK:
                long customerId = 0;
                if (redundantTemplateTypeEnum == COMMUNICATE_PLAN) {
                    customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), 0L);
                }else {
                    customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentTaskEnum.LINK_CUSTOMER.getAttr(), 0L);
                }
                PaasFormDataEntityExt customerEntity = proGetHelp.getByKey(customerId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
                JSONArray customerPhone = FastJsonHelper.getJsonArrOrDefaultFromFormData(customerEntity.getData(), CustomerManagementEnum.PHONE.getAttr(), new JSONArray());
                String customerNameStr = FastJsonHelper.getStringOrDefaultFromFormData(customerEntity.getData(), CustomerManagementEnum.NAME.getAttr(), "");
                if(explainMap!=null) {
                    fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                }
                // 判断客户电话子表单是否启用
                FieldAttrEntity customerFieldAttr = null;
                PaasFormExplainEntity customerExplainEntity = paasFormExplainModel.getByFormId(customerEntity.getFormId(),corpid);
                if(Objects.nonNull(customerExplainEntity) && Objects.equals(customerExplainEntity.getDel(), DelEnum.NORMAL.getDel())) {
                    String customerExplains = customerExplainEntity.getExplains();
                    if(Objects.nonNull(customerExplains)){
                        Map<String, FieldAttrEntity> customerExplainMap = ExplainUtil.getExplainMap(customerExplains, null);
                        if(customerExplainMap != null){
                            customerFieldAttr = customerExplainMap.get(CustomerManagementEnum.PHONE.getAttr());
                        }
                    }
                }
                if(Objects.equals(customerFieldAttr.getIsOpen(), BasicConstant.ONE) && Objects.equals(customerFieldAttr.getVisible(), BasicConstant.ONE)){
                    isOpen = true;
                }
                //获取子表单里的手机字段
                fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                if(isOpen){
                    mainPhoneList = handleDialPhone(customerPhone, customerNameStr, RedundantTemplateTypeEnum.CUSTOMER.getCode(), customerId,handlerExplainDTO,fieldAttrEntity, handlerExplainDTO.getLoginUser());
                }
                SearchSourceBuilder sourceBuilder1 = new SearchSourceBuilder();
                BoolQueryBuilder boolQueryBuilder1 = boolQuery();
                boolQueryBuilder1.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder1.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder1.filter(termQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME), customerId));
                boolQueryBuilder1.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
                sourceBuilder1.query(boolQueryBuilder1);
                PageRequest pageRequest1 = EsUtil.setPage(sourceBuilder1, 1, EsNormalConstant.FIND_NUM);
                SearchRequest searchRequest1 = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
                searchRequest1.source(sourceBuilder1);
                XbbAggregatedPage<PaasFormDataEntityExt> contacts = xbbElasticsearchRestTemplate.queryForPages(pageRequest1, searchRequest1, PaasFormDataEntityExt.class);


                Map<String, FieldAttrEntity> contractsExplainMap = saasListHelp.getExplains(RedundantTemplateTypeEnum.CONTACT.getCode(),corpid);
                Boolean communicatePlanNameSee = false;
                FieldAttrEntity communicatePlanNameField = contractsExplainMap.get(ContactEnum.NAME.getAttr());
                if (Objects.nonNull(communicatePlanNameField)) {
                    communicatePlanNameSee = !ExplainUtil.fieldAttrHide(communicatePlanNameField, handlerExplainDTO);
                }
                Boolean communicatePlanSerlaiNoSee = false;
                FieldAttrEntity communicatePlanSerlaiNoField = contractsExplainMap.get(BasicConstant.SERIAL_NO);
                if (Objects.nonNull(communicatePlanSerlaiNoField)) {
                    communicatePlanSerlaiNoSee = !ExplainUtil.fieldAttrHide(communicatePlanSerlaiNoField, handlerExplainDTO);
                }
                Boolean communicatePlanDepartMentSee = false;
                FieldAttrEntity communicatePlanDepartMentField = contractsExplainMap.get(BasicConstant.SERIAL_NO);
                if (Objects.nonNull(communicatePlanDepartMentField)) {
                    communicatePlanDepartMentSee = !ExplainUtil.fieldAttrHide(communicatePlanDepartMentField, handlerExplainDTO);
                }
                Boolean communicatePlanCustomerNameSee = false;
                FieldAttrEntity communicatePlanCustomerNameField = contractsExplainMap.get(ContactEnum.CUSTOMER_NAME.getAttr());
                if (Objects.nonNull(communicatePlanCustomerNameField)) {
                    communicatePlanCustomerNameSee = !ExplainUtil.fieldAttrHide(communicatePlanCustomerNameField, handlerExplainDTO);
                }
                Boolean communicatePlanContactEmailSee = false;
                FieldAttrEntity communicatePlanContactEmailField = contractsExplainMap.get(ContactEnum.EMAIL.getAttr());
                if (Objects.nonNull(communicatePlanContactEmailField)) {
                    communicatePlanContactEmailSee = !ExplainUtil.fieldAttrHide(communicatePlanContactEmailField, handlerExplainDTO);
                }
                Boolean communicatePlanContactQQSee = false;
                FieldAttrEntity communicatePlanContactQQField = contractsExplainMap.get(ContactEnum.QQ.getAttr());
                if (Objects.nonNull(communicatePlanContactQQField)) {
                    communicatePlanContactQQSee = !ExplainUtil.fieldAttrHide(communicatePlanContactQQField, handlerExplainDTO);
                }
                Boolean communicatePlanContactZipCodeSee = false;
                FieldAttrEntity communicatePlanContactZipCodeField = contractsExplainMap.get(ContactEnum.ZIP_CODE.getAttr());
                if (Objects.nonNull(communicatePlanContactZipCodeField)) {
                    communicatePlanContactZipCodeSee = !ExplainUtil.fieldAttrHide(communicatePlanContactZipCodeField, handlerExplainDTO);
                }
                Boolean communicatePlanContactSexSee = false;
                FieldAttrEntity communicatePlanContactSexField = contractsExplainMap.get(ContactEnum.SEX.getAttr());
                if (Objects.nonNull(communicatePlanContactSexField)) {
                    communicatePlanContactSexSee = !ExplainUtil.fieldAttrHide(communicatePlanContactSexField, handlerExplainDTO);
                }
                Boolean communicatePlanContactHobbiesSee = false;
                FieldAttrEntity communicatePlanContactHobbiesField = contractsExplainMap.get(ContactEnum.HOBBIES.getAttr());
                if (Objects.nonNull(communicatePlanContactHobbiesField)) {
                    communicatePlanContactHobbiesSee = !ExplainUtil.fieldAttrHide(communicatePlanContactHobbiesField, handlerExplainDTO);
                }
                Boolean communicatePlanContactDepartSee = false;
                FieldAttrEntity communicatePlanContactDepartField = contractsExplainMap.get(ContactEnum.DEPARTMENT.getAttr());
                if (Objects.nonNull(communicatePlanContactDepartField)) {
                    communicatePlanContactDepartSee = !ExplainUtil.fieldAttrHide(communicatePlanContactDepartField, handlerExplainDTO);
                }
                Boolean communicatePlanContactPositionSee = false;
                FieldAttrEntity communicatePlanContactPositionField = contractsExplainMap.get(ContactEnum.POSITION.getAttr());
                if (Objects.nonNull(communicatePlanContactPositionField)) {
                    communicatePlanContactPositionSee = !ExplainUtil.fieldAttrHide(communicatePlanContactPositionField, handlerExplainDTO);
                }
                Boolean communicatePlanContactLevelSee = false;
                FieldAttrEntity communicatePlanContactLevelField = contractsExplainMap.get(ContactEnum.LEVEL.getAttr());
                if (Objects.nonNull(communicatePlanContactLevelField)) {
                    communicatePlanContactLevelSee = !ExplainUtil.fieldAttrHide(communicatePlanContactLevelField, handlerExplainDTO);
                }
                Boolean communicatePlanContactImportDegreeSee = false;
                FieldAttrEntity communicatePlanContactImportDegreeField = contractsExplainMap.get(ContactEnum.IMPORTANT_DEGREE.getAttr());
                if (Objects.nonNull(communicatePlanContactImportDegreeField)) {
                    communicatePlanContactImportDegreeSee = !ExplainUtil.fieldAttrHide(communicatePlanContactImportDegreeField, handlerExplainDTO);
                }
                Boolean communicatePlanContactRelationshipSee = false;
                FieldAttrEntity communicatePlanContactRelationshipField = contractsExplainMap.get(ContactEnum.RELATIONSHIP.getAttr());
                if (Objects.nonNull(communicatePlanContactRelationshipField)) {
                    communicatePlanContactRelationshipSee = !ExplainUtil.fieldAttrHide(communicatePlanContactRelationshipField, handlerExplainDTO);
                }
                Boolean communicatePlanContactIntimateDegreeSee = false;
                FieldAttrEntity communicatePlanContactIntimateDegreeField = contractsExplainMap.get(ContactEnum.INTIMATE_DEGREE.getAttr());
                if (Objects.nonNull(communicatePlanContactIntimateDegreeField)) {
                    communicatePlanContactIntimateDegreeSee = !ExplainUtil.fieldAttrHide(communicatePlanContactIntimateDegreeField, handlerExplainDTO);
                }
                Boolean communicatePlanContactCreatorIdSee = false;
                FieldAttrEntity communicatePlanContactCreatorIdField = contractsExplainMap.get(ContactEnum.CREATOR_ID.getAttr());
                if (Objects.nonNull(communicatePlanContactCreatorIdField)) {
                    communicatePlanContactCreatorIdSee = !ExplainUtil.fieldAttrHide(communicatePlanContactCreatorIdField, handlerExplainDTO);
                }
                Boolean communicatePlanContactAddTimeSee = false;
                FieldAttrEntity communicatePlanContactAddTimeField = contractsExplainMap.get(ContactEnum.ADD_TIME.getAttr());
                if (Objects.nonNull(communicatePlanContactAddTimeField)) {
                    communicatePlanContactAddTimeSee = !ExplainUtil.fieldAttrHide(communicatePlanContactAddTimeField, handlerExplainDTO);
                }
                Boolean communicatePlanContactUpdateTimeSee = false;
                FieldAttrEntity communicatePlanContactUpdateTimeField = contractsExplainMap.get(ContactEnum.UPDATE_TIME.getAttr());
                if (Objects.nonNull(communicatePlanContactUpdateTimeField)) {
                    communicatePlanContactUpdateTimeSee = !ExplainUtil.fieldAttrHide(communicatePlanContactUpdateTimeField, handlerExplainDTO);
                }
                // 跳转穿透
                Map<Long, DataDetailTabPojo> tabPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                // 标签
                Map<Long, JSONArray> tagMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormDataEntityExt contactEntity : contacts.getContent()) {
                    Long contactId = contactEntity.getId();
                    JSONObject dataList = contactEntity.getData();
                    if(!communicatePlanNameSee){
                        dataList.remove(SupplierContactEnum.NAME.getAttr());
                    }
                    JSONArray contactPhone = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, ContactEnum.PHONE.getAttr(), new JSONArray());
                    String contactNameStr = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ContactEnum.NAME.getAttr(), "");
                    if(contractsExplainMap!=null) {
                        fieldAttrEntity = contractsExplainMap.get(ContactEnum.PHONE.getAttr());
                    }
                    //获取子表单里的手机字段
                    fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                    contactPhoneList.addAll(handleDialPhone(contactPhone, contactNameStr, RedundantTemplateTypeEnum.CONTACT.getCode(), contactId,handlerExplainDTO,fieldAttrEntity, handlerExplainDTO.getLoginUser()));

                    // 获取关联的联系人的表单id
                    Long contactsForm = contactEntity.getFormId();
                    //跳转需要的参数
                    DataDetailTabPojo dataDetailTabPojo = new DataDetailTabPojo();
                    dataDetailTabPojo.setAppId(contactEntity.getAppId());
                    dataDetailTabPojo.setDataId(contactId);
                    dataDetailTabPojo.setMenuId(contactEntity.getMenuId());
                    dataDetailTabPojo.setFormId(contactsForm);
                    dataDetailTabPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    dataDetailTabPojo.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
                    tabPojoMap.put(contactId, dataDetailTabPojo);

                    if(!Objects.equals(contactsForm, 0L)){
                        // 获取联系人表单字段解释
                        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(contactsForm, corpid);
                        // 获取联系人关联的数据标签
                        List<SummaryDataPoJo> labels = JSONArray.parseArray(paasFormEntityExt.getLabels(), SummaryDataPoJo.class);
                        labels = labels == null ? new ArrayList<>() : labels;
                        // 标签
                        // 字段高级可见
                        Map<String, Boolean> contactVisiableMap = new HashMap<>();
                        contactVisiableMap.put(ContactEnum.NAME.getAttr(), communicatePlanNameSee);
                        contactVisiableMap.put(BasicConstant.SERIAL_NO, communicatePlanSerlaiNoSee);
                        contactVisiableMap.put("departmentId", communicatePlanDepartMentSee);
                        contactVisiableMap.put(ContactEnum.CUSTOMER_NAME.getAttr(), communicatePlanCustomerNameSee);
                        contactVisiableMap.put(ContactEnum.EMAIL.getAttr(), communicatePlanContactEmailSee);
                        contactVisiableMap.put(ContactEnum.QQ.getAttr(),  communicatePlanContactQQSee);
                        contactVisiableMap.put(ContactEnum.ZIP_CODE.getAttr(), communicatePlanContactZipCodeSee);
                        contactVisiableMap.put(ContactEnum.SEX.getAttr(), communicatePlanContactSexSee);
                        contactVisiableMap.put(ContactEnum.HOBBIES.getAttr(), communicatePlanContactHobbiesSee);
                        contactVisiableMap.put(ContactEnum.DEPARTMENT.getAttr(), communicatePlanContactDepartSee);
                        contactVisiableMap.put(ContactEnum.POSITION.getAttr(), communicatePlanContactPositionSee);
                        contactVisiableMap.put(ContactEnum.LEVEL.getAttr(), communicatePlanContactLevelSee);
                        contactVisiableMap.put(ContactEnum.IMPORTANT_DEGREE.getAttr(), communicatePlanContactImportDegreeSee);
                        contactVisiableMap.put(ContactEnum.RELATIONSHIP.getAttr(), communicatePlanContactRelationshipSee);
                        contactVisiableMap.put(ContactEnum.INTIMATE_DEGREE.getAttr(), communicatePlanContactIntimateDegreeSee);
                        contactVisiableMap.put(ContactEnum.CREATOR_ID.getAttr(), communicatePlanContactCreatorIdSee);
                        contactVisiableMap.put(ContactEnum.ADD_TIME.getAttr(), communicatePlanContactAddTimeSee);
                        contactVisiableMap.put(ContactEnum.UPDATE_TIME.getAttr(), communicatePlanContactUpdateTimeSee);
                        JSONArray tags = handleMobileTag(contactEntity, contactEntity.getSerialNo(), customerEntity.getDepartmentId(), labels, dataList, contractsExplainMap, contactVisiableMap, redundantTemplateTypeEnum);
                        tagMap.put(contactId, tags);
                    }
                }
                contactPhoneList.forEach(item -> {
                    Long contactId = item.getDataId();
                    if(tabPojoMap.containsKey(contactId)){
                        item.setEntity(tabPojoMap.get(contactId));
                    }
                    if(tagMap.containsKey(contactId)){
                        item.setTags(tagMap.get(contactId));
                    }
                });
                break;
            case CLUE:
                JSONArray cluePhoneArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ClueEnum.PHONE.getAttr(), new JSONArray());
                String clueName = FastJsonHelper.getStringOrDefaultFromFormData(data, ClueEnum.COMPANY_NAME.getAttr(), "");
                Integer cluePublic = getIntegerOrDefaultFromFormData(data, ClueEnum.IS_PUBLIC.getAttr(), 0);
                Boolean publicCanSee = true;
                if(explainMap!=null) {
                    fieldAttrEntity = explainMap.get(ClueEnum.PHONE.getAttr());
                    if (!Objects.equals(fieldAttrEntity.getPublicPool(), BasicConstant.ONE)) {
                        publicCanSee = false;
                    }
                }
                // 判断子表单是否启用
                if(Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ONE) && Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ONE)){
                    isOpen = true;
                }
                //获取子表单里的手机字段
                fieldAttrEntity = commonHelp.getSubFormAttr(fieldAttrEntity);
                if (Objects.equals(cluePublic, BasicConstant.ONE) && !publicCanSee) {
                    fieldAttrEntity.setVisible(0);
                }
                if(isOpen){
                    mainPhoneList.addAll(handleDialPhone(cluePhoneArr, clueName, RedundantTemplateTypeEnum.CLUE.getCode(), paasFormDataEntityExt.getId(),handlerExplainDTO,fieldAttrEntity, handlerExplainDTO.getLoginUser()));
                }
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        phoneForDialGetVO.setMainPhoneList(mainPhoneList);
        phoneForDialGetVO.setContactPhoneList(contactPhoneList);
        boolean isActiveCall = callCenterCommonService.isOpenCallDingTalk(corpid, phoneForDialGetDTO.getUserId());
        phoneForDialGetVO.setIsCallCenter(isActiveCall);
        IsActiveAliyunCallVO activeAliyunCall1 = callCenterCommonService.isActiveAliyunCall(corpid, phoneForDialGetDTO.getUserId());
        boolean activeAliyunCall = false;
        Integer openDoubleCall = 0;
        if (Objects.nonNull(activeAliyunCall1)) {
            activeAliyunCall = activeAliyunCall1.IsActiveAliyunAndHasRole();
            openDoubleCall = Objects.nonNull(activeAliyunCall1.getOpenDoubleCall()) ? activeAliyunCall1.getOpenDoubleCall() : 0;
        }
        phoneForDialGetVO.setIsAliyunCallCenter(activeAliyunCall);
        phoneForDialGetVO.setOpenDoubleCall(openDoubleCall);
        return phoneForDialGetVO;
    }


    /***
     * 联系人标签处理
     *
     * @param contactEntity 联系人数据/供应商联系人
     * @param serialNo 联系人编号
     * @param depId 数据部门id
     * @param labels 联系人标签
     * @param dataList 联系人数据
     * @param explainMap 联系人解释
     * @param contactVisiableMap 字段权限
     * @param redundantTemplateTypeEnum 业务类型
     * @throws
     * @return com.alibaba.fastjson.JSONArray
     * @author hongxiao
     * @date 2023-03-28 17:32
     * @since
     * @version
     */
    private JSONArray handleMobileTag(PaasFormDataEntityExt contactEntity, String serialNo, Long depId, List<SummaryDataPoJo> labels, JSONObject dataList, Map<String, FieldAttrEntity> explainMap,
                                      Map<String, Boolean> contactVisiableMap, RedundantTemplateTypeEnum redundantTemplateTypeEnum) throws XbbException {
        JSONArray tags = new JSONArray();
        for (SummaryDataPoJo item : labels) {
            String attr = item.getAttr();
            FieldAttrEntity fieldAttr = explainMap.get(attr);
            if (fieldAttr == null) {
                continue;
            }
            Integer fieldType = fieldAttr.getFieldType();
            Object tag = dataList.get(attr);
            JSONObject object = new JSONObject();

            if (FieldTypeEnum.COMBO.getType().equals(fieldType) || FieldTypeEnum.RADIO_GROUP.getType().equals(fieldType)) {
                List<ItemPoJo> itemPoJos = fieldAttr.getItems();
                if(CollectionsUtil.isNotEmpty(itemPoJos)){
                    for (ItemPoJo itemPoJo : itemPoJos){
                        if (Objects.equals(tag, itemPoJo.getValue())) {
                            tag = itemPoJo.getText();
                        }
                    }
                }
            }

            if(Objects.equals(attr, StringConstant.CREATOR_ID)){
                UserEntity user = userModel.getByKey(contactEntity.getCreatorId(), contactEntity.getCorpid());
                tag = Objects.nonNull(user) ? user.getName() : "";
            }
            if(Objects.equals(attr, StringConstant.ADD_TIME)){
                tag = DateUtil.getString(contactEntity.getAddTime() * 1000L, DateUtil.SDFYMDHM);
            }
            if(Objects.equals(attr, StringConstant.UPDATE_TIME)){
                tag = DateUtil.getString(contactEntity.getUpdateTime() * 1000L, DateUtil.SDFYMDHM);
            }
            if (RedundantTemplateTypeEnum.SUPPLIER == redundantTemplateTypeEnum) {
                if(Objects.equals(attr, SupplierContactEnum.SUPPLIER_ID.getAttr())){
                    tag = FastJsonHelper.getStringFromFormData(dataList, SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr());
                }
                if(Objects.equals(attr, SupplierContactEnum.SEX.getAttr())){
                    Integer code = getIntegerFromFormData(dataList, SupplierContactEnum.SEX.getAttr());
                    tag = StringUtil.getSexStr(code);
                }
                if(Objects.equals(attr, SupplierContactEnum.LEVEL.getAttr())){
                    ContactLevelEnum contactLevelEnum = ContactLevelEnum.getByCode(FastJsonHelper.getStringFromFormData(dataList, SupplierContactEnum.LEVEL.getAttr()));
                    tag = contactLevelEnum == null ? null : contactLevelEnum.getName();
                }
            } else {
                if(Objects.equals(attr, ContactEnum.CUSTOMER_NAME.getAttr())){
                    tag = FastJsonHelper.getStringFromFormData(dataList, ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
                }
                if(Objects.equals(attr, ContactEnum.LEVEL.getAttr())){
                    ContactLevelEnum contactLevelEnum = ContactLevelEnum.getByCode(FastJsonHelper.getStringFromFormData(dataList, ContactEnum.LEVEL.getAttr()));
                    tag = contactLevelEnum == null ? null : contactLevelEnum.getName();
                }
                if(Objects.equals(attr, ContactEnum.SEX.getAttr())){
                    Integer code = getIntegerFromFormData(dataList, ContactEnum.SEX.getAttr());
                    tag = StringUtil.getSexStr(code);
                }
                if(Objects.equals(attr, ContactEnum.IMPORTANT_DEGREE.getAttr())){
                    Integer importDegree = getIntegerOrDefaultFromFormData(dataList, ContactEnum.IMPORTANT_DEGREE.getAttr(), 0);
                    tag = importDegree == 0 ? null : supplierService.transferLevel2Chinese(importDegree);
                }
                if(Objects.equals(attr, ContactEnum.INTIMATE_DEGREE.getAttr())){
                    Integer intimateGegree = getIntegerOrDefaultFromFormData(dataList, ContactEnum.INTIMATE_DEGREE.getAttr(), 0);
                    tag = intimateGegree == 0 ? null : supplierService.transferLevel2Chinese(intimateGegree);
                }
                if(Objects.equals(attr, ContactEnum.RELATIONSHIP.getAttr())){
                    String relationShip = FastJsonHelper.getStringFromFormData(dataList, ContactEnum.RELATIONSHIP.getAttr());
                    FieldAttrEntity relationShipFieldAttr = explainMap.getOrDefault(ContactEnum.RELATIONSHIP.getAttr(), new FieldAttrEntity());
                    if (relationShipFieldAttr != null && relationShipFieldAttr.getItems() != null && relationShip != null) {
                        JSONObject json = new JSONObject();
                        json.put(relationShipFieldAttr.getAttr(),relationShip);
                        tag = ItemUtil.getCustomItemList(relationShipFieldAttr,json).toString();
                    }
                }
                if(Objects.equals(attr, BasicConstant.SERIAL_NO)){
                    tag = serialNo;
                }
                if(Objects.equals(attr, "departmentId")){
                    DepartmentEntity departmentEntity = departmentModel.getByKey(depId, contactEntity.getCorpid());
                    if (Objects.nonNull(departmentEntity)) {
                        tag = departmentEntity.getName();
                    }
                }
            }

            // 字段高级可见
            Boolean seeFlag = contactVisiableMap.getOrDefault(attr, false);
            tag = !seeFlag ? null : tag;
            tag = tag == null ? "" : tag;
            if (!Objects.equals(tag, "") && !(tag instanceof JSONArray)) {  // 后面条件是去掉前台展示[]的bug
                object.put("value", tag);
                object.put("type", "normal");
                tags.add(object);
            }
        }
        return tags;
    }

    /**
     * 处理移动端联系人拨号
     *
     * @param phoneJsonArray 电话
     * @param name           显示名称
     * @param businessType   业务类型
     * @param dataId         数据id
     * @return 异常
     */
    @Override
    public List<MobileDetailDialPhonePojo> handleDialPhone(JSONArray phoneJsonArray, String name, Integer businessType, Long dataId, HandlerExplainDTO handlerExplainDTO,FieldAttrEntity fieldAttrEntity, UserVO loginUser) throws XbbException {
        return commonHelp.handleDialPhone(phoneJsonArray, name, businessType, dataId,handlerExplainDTO,fieldAttrEntity, loginUser);
    }

    @Override
    public void handelMobileWorkFlow(UserVO loginUser, Integer businessType, FormDataGetVO formDataGetVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        Integer distributorMark = formDataGetVO.getDistributorMark();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, loginUser.getPermSet());
        JSONObject dataList = paasFormDataEntityExt.getData();
        List<TopPermissionsPoJo> topPermissions = formDataGetVO.getTopPermissions();
        if (Objects.isNull(topPermissions)) {
            topPermissions = new ArrayList<>();
            formDataGetVO.setTopPermissions(topPermissions);
        }
        // 获取对应businessType的alias
        Map<String,Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> aliasIn = new ArrayList<>();
        workFlowEnumList.forEach(item -> aliasIn.add(XbbRefTypeEnum.getByCode(item.getBusinessType()).getAlias()));
        params.put("corpid", paasFormDataEntityExt.getCorpid());
        params.put("aliasIn", aliasIn);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put(StringConstant.DISTRIBUTOR_MARK, distributorMark);
        List<PaasMenuEntity> paasMenuEntities = paasMenuModel.findEntitys(params);
        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasMenuEntities.forEach(item-> paasBusinessTypeToName.put(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode(),item.getName()));

        Set<String> loginUserPermSet = loginUser.getPermSet();
        Set<RoleSimpleVO> loginUserRoleSet = loginUser.getRoleSet();
        boolean hasUpdate = true;
        //工单应用是否开启
        Boolean workOrderEnable = false;
        //个人能用的工单模板
        List<WorkOrderFormEntity> workOrderEnableForms;
        Long nowMmodelType = fundSetService.getModelType(paasFormDataEntityExt.getCorpid(),XbbRefTypeEnum.CRM);
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(loginUser, userEntity);
            boolean isBoss = loginUser.isAdminOrBoss();
            boolean isCreator = Objects.equals(paasFormDataEntityExt.getCreatorId(), userEntity.getUserId());
            WorkOrderFlowUserEntity mainUser = workOrderFlowUserService.getMainUser(paasFormDataEntityExt.getId(), paasFormDataEntityExt.getCorpid());
            boolean isMain = false;
            if (Objects.nonNull(mainUser) && Objects.equals(mainUser.getUserId(), loginUser.getUserId())) {
                isMain = true;
            }
            boolean isWorkOrderDispatcher = false;
            boolean isWorkOrderManager = false;
            for (RoleSimpleVO roleSimpleVO : loginUserRoleSet) {
                if (Objects.equals(roleSimpleVO.getId(), RoleEnum.WORKORDER_DISPATCHER.getCode())) {
                    isWorkOrderDispatcher = true;
                }
                if (Objects.equals(roleSimpleVO.getId(), RoleEnum.WORKORDER_MANAGER.getCode())) {
                    isWorkOrderManager = true;
                }
            }

            //工单完成状态可编辑权限
            Boolean isWorkOrderFinishedEdit = ProPermissionHelp.hasThisPermission(loginUser,ProPermissionAliasEnum.WORK_ORDER_FINISHED_EDIT.getAlias());

            Integer shippedFlag = getIntegerOrDefaultFromFormData(dataList, WorkOrderEnum.SHIP_STATUS.getAttr(), WorkOrderShipStatusEnum.EMPTY.getCode());
            for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                if (Objects.equals(workFlowEnum, WorkFlowEnum.WORK_ORDER_DETAIL_EDIT)) {
//编辑权限
                    if (Objects.equals(paasFormDataEntityExt.getStatus(), WorkOrderStatusEnum.FINISH.getCode())) {
                        //工单"完成"状态，仅设置了工单完成状态可编辑权限情况下可编辑
                        if (!isWorkOrderFinishedEdit) {
                            continue;
                        }
                    } else {
                        //	创建人，老板、超管等最高权限人员，主负责人，派单员，工单主管。其他角色可自定义添加此权限。
                        if (!(isCreator || isBoss || isMain || ((isWorkOrderDispatcher || isWorkOrderManager) || loginUserPermSet.contains(UpdateProPermissionAliasEnum.WORK_ORDER_UPDATE.getAlias())))) {
                            continue;
                        }
                    }
                }
                if (Objects.equals(workFlowEnum, WorkFlowEnum.WORK_ORDER_DETAIL_DEL)) {
                    if (!(isCreator || isBoss || isMain || (isWorkOrderManager && loginUserPermSet.contains(DeleteProPermissionAliasEnum.WORK_ORDER_DEL.getAlias())) || loginUserPermSet.contains(DeleteProPermissionAliasEnum.WORK_ORDER_DEL.getAlias()))) {
                        continue;
                    }
                }
                // 过滤掉全部出库和无关联产品的情况
                if ((Objects.equals(shippedFlag, WorkOrderShipStatusEnum.SHIPPED.getCode()) || Objects.equals(shippedFlag, WorkOrderShipStatusEnum.EMPTY.getCode()))
                        && Objects.equals(workFlowEnum, WorkFlowEnum.WORK_ORDER_OUTSTOCK)) {
                    continue;
                }
                TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                    changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                }
                topPermissions.add(topPermissionsPoJo);
            }
//            //编辑权限
//            if (Objects.equals(paasFormDataEntityExt.getStatus(), WorkOrderStatusEnum.FINISH.getCode())) {
//                //工单"完成"状态，仅超管、老板可编辑
//                if (isBoss) {
//                    TopPermissionsPoJo editPoJo = new TopPermissionsPoJo(OperateTypeEnum.EDIT.getAlias(), OperateTypeEnum.EDIT.getName(), businessType, OperateTypeEnum.EDIT.getAlias());
//                    topPermissions.add(editPoJo);
//                }
//            } else {
//                //	创建人，老板、超管等最高权限人员，主负责人，派单员，工单主管。其他角色可自定义添加此权限。
//                if (isCreator || isBoss || isMain || isWorkOrderDispatcher || isWorkOrderManager || loginUserPermSet.contains(UpdateProPermissionAliasEnum.WORK_ORDER_UPDATE.getAlias())) {
//                    TopPermissionsPoJo editPoJo = new TopPermissionsPoJo(OperateTypeEnum.EDIT.getAlias(), OperateTypeEnum.EDIT.getName(), businessType, OperateTypeEnum.EDIT.getAlias());
//                    topPermissions.add(editPoJo);
//                }
//            }
//            //删除权限
//            if (loginUserPermSet.contains(DeleteProPermissionAliasEnum.WORK_ORDER_DEL.getAlias())) {
//                TopPermissionsPoJo deletePoJo = new TopPermissionsPoJo(OperateTypeEnum.DELETE.getAlias(), OperateTypeEnum.DELETE.getName(), businessType, OperateTypeEnum.DELETE.getAlias());
//                topPermissions.add(deletePoJo);
//            }
        } else if (Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType)) {
            String creatorId = paasFormDataEntityExt.getCreatorId();
            UserEntity userEntity = userModel.getByKey(loginUser.getUserId(),loginUser.getCorpid());
            String roleIds = userEntity.getRoleIds();
            List<String> roleIdList = StringUtil.roleIdToList(roleIds);
            String adminStr =  String.valueOf(RoleEnum.ADMIN.getCode());
            String bossStr = String.valueOf(RoleEnum.BOSS.getCode());
            boolean rolePermission = Objects.isNull(roleIdList) ? false : roleIdList.contains(adminStr) || roleIdList.contains(bossStr);
            if (Objects.equals(creatorId, loginUser.getUserId())) {
                if (loginUserPermSet.contains(ProPermissionAliasEnum.WORK_REPORT_UPDATE.getAlias())) {
                    TopPermissionsPoJo editPoJo = new TopPermissionsPoJo(OperateTypeEnum.EDIT.getAlias(), OperateTypeEnum.EDIT.getName(), businessType, OperateTypeEnum.EDIT.getAlias());
                    topPermissions.add(editPoJo);
                }
                if (loginUserPermSet.contains(ProPermissionAliasEnum.WORK_REPORT_DELETE.getAlias())) {
                    TopPermissionsPoJo deletePoJo = new TopPermissionsPoJo(OperateTypeEnum.DELETE.getAlias(), OperateTypeEnum.DELETE.getName(), businessType, OperateTypeEnum.DELETE.getAlias());
                    topPermissions.add(deletePoJo);
                }
                if (loginUserPermSet.contains(ProPermissionAliasEnum.WORK_REPORT_PRINT.getAlias())) {
                    TopPermissionsPoJo printPoJo = new TopPermissionsPoJo(PaasConstant.PRINTSTRING, I18nMessageUtil.getMessage(PaasConstant.PRINT), businessType, PaasConstant.PRINTSTRING);
                    topPermissions.add(printPoJo);
                }
            } else{
                if(rolePermission){
                    // 超管 老板可以删除任一工作报告
                    TopPermissionsPoJo deletePoJo = new TopPermissionsPoJo(OperateTypeEnum.DELETE.getAlias(), OperateTypeEnum.DELETE.getName(), businessType, OperateTypeEnum.DELETE.getAlias());
                    topPermissions.add(deletePoJo);
                    TopPermissionsPoJo printPoJo = new TopPermissionsPoJo(PaasConstant.PRINTSTRING, I18nMessageUtil.getMessage(PaasConstant.PRINT), businessType, PaasConstant.PRINTSTRING);
                    topPermissions.add(printPoJo);
                }
            }

        } else {
            List<Integer> noEditButtonBusinessType = Arrays.asList(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), XbbRefTypeEnum.EXPENSE.getCode(), XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode());

            Boolean isExpenseManagement = Objects.equals(businessType, XbbRefTypeEnum.REIMBURSEMENT_FORM.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.EXPENSE.getCode());
            boolean editPermission = true;
            //boolean editPermission = saasDetailPermissionHelp.teamMembersCheckEditPermission(loginUser, ,paasFormDataEntityExt, businessType, );
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            // 信用管理相关表单无编辑和删除按钮
            boolean creditFlag = Objects.equals(businessType, XbbRefTypeEnum.CREDIT_LIMIT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode());
            if (!noEditButtonBusinessType.contains(businessType) && !isExpenseManagement) {
                //编辑权限判断
                UpdateProPermissionAliasEnum updateProPermissionAliasEnum;
                if (sheetFlag) {
                    updateProPermissionAliasEnum = UpdateProPermissionAliasEnum.getByCode(sheetTypeEnum.getXbbRefTypeEnum().getCode());
                } else {
                    updateProPermissionAliasEnum = UpdateProPermissionAliasEnum.getByCode(businessType);
                }
                hasUpdate = (Objects.nonNull(updateProPermissionAliasEnum) && loginUserPermSet.contains(updateProPermissionAliasEnum.getAlias()) && editPermission)
                        || Objects.isNull(updateProPermissionAliasEnum);
                if (hasUpdate && !creditFlag){
                    TopPermissionsPoJo editPoJo = new TopPermissionsPoJo(OperateTypeEnum.EDIT.getAlias(), OperateTypeEnum.EDIT.getName(), businessType, OperateTypeEnum.EDIT.getAlias());
                    editPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(editPoJo.getBusinessType()));
                    editPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(editPoJo);
                }
            }
            //没有删除功能的业务
            boolean noDel = Objects.equals(businessType, XbbRefTypeEnum.OTHER_INCOME.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.OTHER_EXPENSE.getCode());
            //删除权限判断
            DeleteProPermissionAliasEnum deleteProPermissionAliasEnum = DeleteProPermissionAliasEnum.getByCode(businessType);
            boolean hasDel = (Objects.nonNull(deleteProPermissionAliasEnum) && loginUserPermSet.contains(deleteProPermissionAliasEnum.getAlias()))
                    || Objects.isNull(deleteProPermissionAliasEnum);
            //经销商类型，销项发票、回款单无删除按钮
            boolean specialHasDel = !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark) || (!sheetFlag && !Objects.equals(businessType, XbbRefTypeEnum.INVOICE.getCode()));
            // 协同人不应该有删除合同的权限
            if (hasDel && editPermission && !isExpenseManagement && specialHasDel && !Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode()) && !creditFlag && !noDel) {
                TopPermissionsPoJo deletePoJo = new TopPermissionsPoJo(OperateTypeEnum.DELETE.getAlias(), OperateTypeEnum.DELETE.getName(), businessType, OperateTypeEnum.DELETE.getAlias());
                deletePoJo.setDistributorMark(distributorMark);
                deletePoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(deletePoJo.getBusinessType()));
                topPermissions.add(deletePoJo);
            }
            // 打印按钮
            PrintProPermissionAliasEnum printProPermissionAliasEnum = PrintProPermissionAliasEnum.getByCode(businessType);
            boolean hasPrint = Objects.nonNull(printProPermissionAliasEnum) && loginUserPermSet.contains(printProPermissionAliasEnum.getAlias());
            if (hasPrint ) {
                TopPermissionsPoJo printPoJo = new TopPermissionsPoJo("print", I18nMessageUtil.getMessage(PaasConstant.PRINT), businessType, "print");
                printPoJo.setDistributorMark(distributorMark);
                printPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(printPoJo.getBusinessType()));
                topPermissions.add(printPoJo);
            }
        }
        //进项销项发票实事查询开票金额
        double invoiceAmount = 0;
        String corpid = loginUser.getCorpid();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> subIdList = new ArrayList<>();
        param.put("corpid",loginUser.getCorpid());
        param.put("del",BasicConstant.ZERO);
        param.put("isCancel",BasicConstant.ZERO);
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        Boolean contractOrPurchaseCanInvoice = invoiceCommonHelper.checkContractOrPurchaseInvoice(paasFormDataEntityExt,corpid,redundantTemplateTypeEnum);
        Long nowModelType = fundSetService.getModelType(corpid,XbbRefTypeEnum.CRM);
        Long modelType = paasFormDataEntityExt.getSysLong10();
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                Integer isArchived = getIntegerOrDefaultFromFormData(dataList, CustomerManagementEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                Integer isPublic = getIntegerOrDefaultFromFormData(dataList, CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                Integer del = paasFormDataEntityExt.getDel();
                if (Objects.equals(del, DelEnum.DELETE.getDel())) {
                    topPermissions.removeIf(pojo-> Objects.equals(pojo.getAttr(), OperateTypeEnum.DELETE.getAlias())
                            || Objects.equals(pojo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (!hasUpdate && (Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_ARCHIVED) || Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_CANCEL_ARCHIVED))) {
                        continue;
                    }
                    if (Objects.equals(isArchived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_ARCHIVED)) {
                        continue;
                    } else if (Objects.equals(isArchived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_CANCEL_ARCHIVED)) {
                        continue;
                    }
                    if (Objects.equals(isPublic, BasicConstant.ONE) || Objects.equals(del, DelEnum.DELETE.getDel())) {
                        continue;
                    }
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_PAYMENT) && !Objects.equals(nowMmodelType, ModelTypeEnum.PLAN.getCode())) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case CLUE:
                Integer archived = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                Integer publicFlag = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                String clusStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ClueEnum.CLUE_STATUS.getAttr(), "");
                if (Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel())) {
                    topPermissions.removeIf(pojo-> Objects.equals(pojo.getAttr(), OperateTypeEnum.DELETE.getAlias())
                            || Objects.equals(pojo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(publicFlag, BasicConstant.ONE) || Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel())) {
                        continue;
                    }
                    if (!hasUpdate && (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_ARCHIVED) || Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_CANCEL_ARCHIVED))) {
                        continue;
                    }
                    if (Objects.equals(archived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_ARCHIVED)) {
                        continue;
                    } else if (Objects.equals(archived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_CANCEL_ARCHIVED)) {
                        continue;
                    }
                    if (Objects.equals(clusStatus, ClueStatusEnum.INVALID.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_INVALID)) {
                        continue;
                    }
                    if (Objects.equals(clusStatus, ClueStatusEnum.PENDING.getCode()) || Objects.equals(clusStatus, ClueStatusEnum.FOLLOWING_UP.getCode()) || Objects.equals(clusStatus, ClueStatusEnum.TRANSFORMED.getCode())) {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_FOLLOW)) {
                            continue;
                        }
                    }
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_TRANSFORM) && (Objects.equals(clusStatus, ClueStatusEnum.TRANSFORMED.getCode()) || Objects.equals(clusStatus, ClueStatusEnum.INVALID.getCode()))) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_TRANSFORM)) {
                        if (Objects.equals(clusStatus, ClueStatusEnum.TRANSFORMED.getCode())) {
                            // 线索状态为已转换时，不展示转换操作按钮
                            continue;
                        }
                        // 不需要改名字
                        topPermissions.add(topPermissionsPoJo);
                        continue;
                    }
                    changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    topPermissions.add(topPermissionsPoJo);
                }

                break;
            case CONTRACT:
                Double amount = getDoubleOrDefaultFromFormData(dataList, ContractEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                Double unFinishAmount = getDoubleOrDefaultFromFormData(dataList, ContractEnum.UN_FINISH_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                param.put("contractId",paasFormDataEntityExt.getId());
                List<InvoiceRelationshipEntity> invoiceRelationshipEntityList = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntityList)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationshipEntityList) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                Integer isContractArchived = getIntegerOrDefaultFromFormData(dataList, ContractEnum.ARCHIVED.getAttr(),ArchivedEnum.UN_ARCHIVED.getCode());
                List<ContractProductEntity> contractProductEntityList = contractProductModel.getContractProductByContractIdIn(paasFormDataEntityExt.getCorpid(), 0, Collections.singletonList(paasFormDataEntityExt.getId()));
                boolean notNeedPurchase = contractProductEntityList.isEmpty();
                Integer isAllComing = getIntegerOrDefaultFromFormData(dataList, ContractEnum.ALL_OUT_BOUND.getAttr(), BasicConstant.ZERO);
                String shipstatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ContractEnum.SHIP_STATUS.getAttr(), ShipStatusEnum.UNSHIPPED.getCode());

                PaasMenuEntity prepayMenu = paasMenuModel.getByAlias(XbbRefTypeEnum.PREPAYMENT_BALANCE.getAlias(), corpid);
                //true预付款开启
                boolean prePayFlag = prepayMenu != null && Objects.equals(prepayMenu.getEnable(), BasicConstant.ONE);

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
                    if (esignHelp.addEsignWorkFlow(loginUserPermSet, workFlowPojoList, workFlowEnum,
                            XbbRefTypeEnum.CONTRACT, paasFormDataEntityExt)) {
                        if (workFlowPojoList.isEmpty()) {
                            continue;
                        }
                    }

                    if (!hasUpdate && (Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_ARCHIVED) || Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_CANCEL_ARCHIVED))) {
                        continue;
                    }
                    if (Objects.equals(isContractArchived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_ARCHIVED)) {
                        continue;
                    }
                    if (Objects.equals(isContractArchived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_CANCEL_ARCHIVED)) {
                        continue;
                    }
                    if (notNeedPurchase && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_PURCHASE)) {
                        continue;
                    }
                    if (Objects.equals(isAllComing, BasicConstant.ONE) && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_OUTSTOCK)) {
                        continue;
                    }
                    if (Objects.equals(shipstatus, ShipStatusEnum.CLOSED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_OUTSTOCK)) {
                        continue;
                    }
                    if (invoiceAmount >= amount && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_INVOICE)) {
                        continue;
                    }
                    if ( Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_WRITE_OFF_PREPAYMENT) && !prePayFlag) {
                        continue;
                    }
                    if ( unFinishAmount <= 0D && (Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_WRITE_OFF_PREPAYMENT) || Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_PAYMENT_SHEET) || Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_PAYMENT_SHEET_BAD) )) {
                        continue;
                    }
                    if (!Objects.equals(nowMmodelType, ModelTypeEnum.PLAN.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_PAYMENT)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case ORDER:
                //是否出库完毕
                Integer isOrderAllComing = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, OrderEnum.ALL_OUT_BOUND.getAttr(), BasicConstant.ZERO);
                //出库状态
                String isOrderShipped = FastJsonHelper.getStringOrDefaultFromFormData(dataList, OrderEnum.SHIP_STATUS.getAttr(), ShipStatusEnum.UNSHIPPED.getCode());
                //订单金额
                Double orderAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, OrderEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                Double unOrderFinishAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, OrderEnum.UN_FINISH_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                //订单状态
                Integer orderStatus = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, OrderEnum.STATUS.getAttr(), BasicConstant.ONE);
                if (orderStatus > BasicConstant.TWO){
                    workFlowEnumList.remove(WorkFlowEnum.ORDER_THROUGH);
                    workFlowEnumList.remove(WorkFlowEnum.ORDER_CANCELLATION);
                }
                param.put("contractId",paasFormDataEntityExt.getId());
                List<InvoiceRelationshipEntity> orderInvoiceRelationshipEntityList = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(orderInvoiceRelationshipEntityList)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : orderInvoiceRelationshipEntityList) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                List<ContractProductEntity> orderProductEntityList = contractProductModel.getContractProductByContractIdIn(corpid, 0, Collections.singletonList(paasFormDataEntityExt.getId()));
                boolean orderNotNeedPurchase = orderProductEntityList.isEmpty();
                //工单未开，以及没有可以用的工单模板，移除关联新建工单
                workOrderEnable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                workOrderEnableForms = workOrderFormService.getTemplateWithPermission(loginUser, null, null);
                if (!workOrderEnable || (Objects.nonNull(workOrderEnableForms) && workOrderEnableForms.isEmpty())) {
                    workFlowEnumList.remove(WorkFlowEnum.CONTRACT_WORK_ORDER);
                }

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    //订单状态为待订单审核 待财务审核
                    if(Objects.equals(orderStatus, BasicConstant.ONE) || Objects.equals(orderStatus,BasicConstant.TWO) || Objects.equals(orderStatus,BasicConstant.SIX)){
                        if (Objects.equals(orderStatus, BasicConstant.ONE)){
                            if (!Objects.equals(workFlowEnum,WorkFlowEnum.ORDER_THROUGH) && !Objects.equals(workFlowEnum,WorkFlowEnum.ORDER_CANCELLATION)){
                                continue;
                            }
                        }else if(Objects.equals(orderStatus, BasicConstant.TWO)){
                            if (!Objects.equals(workFlowEnum,WorkFlowEnum.ORDER_CANCELLATION)){
                                continue;
                            }
                        }else if (Objects.equals(orderStatus,BasicConstant.SIX)){
                            continue;
                        }

                    }
                    //订单状态为待收货 已完成 已关闭
                    if (Objects.equals(orderStatus,BasicConstant.FOUR) || Objects.equals(orderStatus,BasicConstant.FIVE) || Objects.equals(orderStatus,BasicConstant.SEVEN)){
                        if (Objects.equals(workFlowEnum,WorkFlowEnum.ORDER_ORDER_OUTSTOCK)){
                            continue;
                        }
                    }

                    if (Objects.equals(isOrderAllComing, BasicConstant.ONE) && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_ORDER_OUTSTOCK)) {
                        continue;
                    }
                    if ((Objects.equals(isOrderShipped, ShipStatusEnum.CLOSED.getCode())&& Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_ORDER_OUTSTOCK))) {
                        continue;
                    }

                    if (invoiceAmount >= orderAmount && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_INVOICE)) {
                        continue;
                    }
                    if (orderNotNeedPurchase && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_PURCHASE)) {
                        continue;
                    }
                    if (unOrderFinishAmount <= BasicConstant.ZERO_DOUBLE && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_PAYMENT)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                //订单状态为已作废 清空所有workfolw
                if (Objects.equals(orderStatus,BasicConstant.SIX)){
                    workFlowEnumList.clear();
                }
                break;
            case ORDER_OUTSTOCK:
                // 出库发货单发货状态
                String expressStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, OrderOutStockEnum.EXPRESS_STATUS.getAttr(), OrderOutStockExpressStatusEnum.TO_BE_DELIVERED.getCode());
                // 是否电子面单发货
                Object taskId = dataList.get(OrderOutStockEnum.ELECTRONIC_TASK_ID.getAttr());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.TO_BE_DELIVERED.getCode()) && (Objects.equals(workFlowEnum,WorkFlowEnum.CANCELL_DELIVERY) || (Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_PRINT)) || (Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_REPEAT_PRINT)))){
                        continue;
                    }
                    if(Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.RECEIVED.getCode())) {
                        continue;
                    }
                    if (Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.TO_BE_RECEIVED.getCode())){
                        if (Objects.equals(workFlowEnum,WorkFlowEnum.NORMAL_DELIVERY) || Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_DELIVERY)){
                            continue;
                        }
                        // 不是电子面单发货的 隐藏电子面打印和电子面单复打按钮
                        if (Objects.isNull(taskId) && (Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_PRINT) || Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_REPEAT_PRINT))){
                            continue;
                        }
                    }
                    if (Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_DELIVERY)){
                        //如果电子面单应用关闭
                        // 获取公司级配置
                        CompanyConfigEntity configEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ELECTRONIC_FACE_SHEET.getAlias(), corpid);
                        if (Objects.isNull(configEntity) || !Objects.equals(BasicConstant.ONE.toString(), configEntity.getConfigValue())){
                            continue;
                        }
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case RETURN:
                String returnStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ReturnEnum.ORDER_STATUS.getAttr(), ReturnStatusEnum.UNDER_REVIEW.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if(Objects.equals(workFlowEnum,WorkFlowEnum.RETURN_INSTOCK) && !Objects.equals(returnStatus,ReturnStatusEnum.PROCESSING.getCode())){
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case SALES_OPPORTUNITY:
                Integer isOpportunityArchived = getIntegerOrDefaultFromFormData(dataList, SalesOpportunityEnum.IS_ARCHIVED.getAttr(), BasicConstant.ZERO);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (!hasUpdate && (Objects.equals(workFlowEnum, WorkFlowEnum.OPPORTUNITY_ARCHIVED) || Objects.equals(workFlowEnum, WorkFlowEnum.OPPORTUNITY_CANCEL_ARCHIVED))) {
                        continue;
                    }
                    if (Objects.equals(isOpportunityArchived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.OPPORTUNITY_ARCHIVED)) {
                        continue;
                    }
                    if (Objects.equals(isOpportunityArchived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.OPPORTUNITY_CANCEL_ARCHIVED)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case PAY_PLAN:
                param.put("payPlanId",paasFormDataEntityExt.getId());
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities) {
                        invoiceAmount = Arith.add(invoiceAmount, purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
                Double payPlanAmount = getDoubleOrDefaultFromFormData(dataList, PayPlanEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                String payPlanStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UNKNOWN.getCode());
                Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, PayPlanEnum.LINK_SUPPLIER.getAttr(), 0L);
//                判断该客户下是否存在预收款余额 且 大于0
                PayBalanceEntity payBalanceEntity = payBalanceModel.getBySupplierId(supplierId,loginUser.getCorpid());
                boolean isPayBalanceAmountExist = false;
                if(payBalanceEntity != null && payBalanceEntity.getAdvancePayBalance() > 0){
                    isPayBalanceAmountExist = true;
                }
                if (Objects.equals(PayPlanStatusEnum.BAD_DEBT.getCode(), payPlanStatus) || Objects.equals(PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode(), payPlanStatus) ) {
                    topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    //判断是否为 已收款/坏账/部分坏账状态
                    boolean noWriteOffPrePay = Objects.equals(payPlanStatus, PayPlanStatusEnum.RECEIVABLES.getCode()) || Objects.equals(payPlanStatus, PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode()) || Objects.equals(payPlanStatus, PayPlanStatusEnum.BAD_DEBT.getCode());
                    if(!isPayBalanceAmountExist || noWriteOffPrePay){
                        if(Objects.equals(workFlowEnum, WorkFlowEnum.WRITE_OFF_PREPAY)){
                            continue;
                        }
                    }
                    if (Objects.equals(PayPlanStatusEnum.BAD_DEBT.getCode(), payPlanStatus) || Objects.equals(PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode(), payPlanStatus)) {
                        // 坏账回款
                        if (!(Objects.equals(workFlowEnum, WorkFlowEnum.PAY_PLAN_REVERT))) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PAY_PLAN_REVERT)) {
                            continue;
                        }
                        if (Objects.equals(PayPlanStatusEnum.RECEIVABLES.getCode(), payPlanStatus) && Objects.equals(workFlowEnum, WorkFlowEnum.PAY_PLAN_BAD)) {
                            continue;
                        }
                    }
                    boolean isInvoice = Objects.equals(payPlanStatus,PayPlanStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(payPlanStatus,PayPlanStatusEnum.RECEIVABLES.getCode()) || Objects.equals(payPlanStatus,PayPlanStatusEnum.PARTIAL_RECEIPTS.getCode());
                    boolean notItemInputInvoice = invoiceAmount < payPlanAmount && isInvoice && contractOrPurchaseCanInvoice;
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.PAY_PLAN_PURCHASE_INVOICE) && !notItemInputInvoice) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.PAY_PLAN_ADD_SHEET)) {
                        boolean paySheetPer = loginUserPermSet.contains(workFlowEnum.getPermission()) && !Objects.equals(payPlanStatus, PayPlanStatusEnum.RECEIVABLES.getCode());
                        if (!paySheetPer) {
                            continue;
                        }
                        // 当操作的attr为payPlanSheet新建付款单走的是付款单单独的add接口
                        topPermissionsPoJo.setAttr(MobileDetailBottomOperationEnum.PAY_PLAN_SHEET.getAttr());
                    }
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case PAYMENT:
                /*
                 * 正常应收款：坏账（仅当未回款金额大于0时展示)、
                 * 红冲（仅当已回款金额大于0时展示）、删除；
                 * 红冲应收款：删除；
                 * 坏账应收款：还原、删除；
                 * 已收款的应收款不能显示红冲应收款
                 */
                param.put("paymentId",paasFormDataEntityExt.getId());
                List<InvoiceRelationshipEntity> invoiceRelationshipEntities = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntities)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationshipEntities) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                Double paymentAmount = getDoubleOrDefaultFromFormData(dataList, PaymentEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                String status = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UNKNOWN.getCode());
                Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, PaymentEnum.CUSTOMER.getAttr(), 0L);
                PaymentBalanceEntity paymentBalanceEntity = paymentBalanceModel.getByCustomerId(customerId, loginUser.getCorpid());
                //判断该客户下是否存在预收款余额 且 大于0
                boolean isBalanceAmountExist = false;
                if(paymentBalanceEntity != null && paymentBalanceEntity.getAdvancePaymentBalance() > 0){
                    isBalanceAmountExist = true;
                }
                if (Objects.equals(PaymentStatusEnum.BAD_DEBT.getCode(), status) || Objects.equals(PaymentStatusEnum.PARTIAL_BAD_DEBT.getCode(), status) ) {
                    topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }
                if(!Objects.equals(PaymentStatusEnum.RED_RECEIVABLES.getCode(),status)){
                    topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.DELETE.getAlias()) &&
                            (!Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode()) || !Objects.equals(modelType, ModelTypeEnum.PLAN.getCode())));
                }
                //未收、部分未收才有核销按钮：true非未收，false未收、部分未收
                boolean nonUnFlag = !PaymentStatusEnum.addPermission(status);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    //判断是否为 已收款/坏账/部分坏账状态
                    boolean noWriteOffPrePayment = Objects.equals(status, PaymentStatusEnum.RECEIVABLES.getCode()) || Objects.equals(status, PaymentStatusEnum.PARTIAL_BAD_DEBT.getCode()) || Objects.equals(status, PaymentStatusEnum.BAD_DEBT.getCode());
                    if(!isBalanceAmountExist || noWriteOffPrePayment){
                        if(Objects.equals(workFlowEnum, WorkFlowEnum.WRITE_OFF_PREPAYMENT)){
                            continue;
                        }
                    }
                    if (nonUnFlag && Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_WRITE_OFF)) {
                        //非未收、部分未收，则无核销应收按钮
                        continue;
                    }
                    // 红冲回款
                    if (Objects.equals(PaymentStatusEnum.BAD_DEBT.getCode(), status) || Objects.equals(PaymentStatusEnum.PARTIAL_BAD_DEBT.getCode(), status)) {
                        // 坏账回款
                        if (!(Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_REVERT))) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_REVERT)) {
                            continue;
                        }
                        // 正常回款
                        if (Objects.equals(PaymentStatusEnum.RECEIVABLES.getCode(), status) && Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_BAD)) {
                            continue;
                        }
                        if(Objects.equals(PaymentStatusEnum.RED_RECEIVABLES.getCode(),status)){
                            if(Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_RED)){
                                continue;
                            }else if (Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_BAD)) {
                                continue;
                            }else if (Objects.equals(workFlowEnum, WorkFlowEnum.WRITE_OFF_PREPAYMENT)) {
                                continue;
                            }
                        }
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_PAYMENT_SHEET)) {
                            boolean paymentSheetPer = loginUserPermSet.contains(workFlowEnum.getPermission()) && (Objects.equals(PaymentStatusEnum.UN_RECEIVABLES.getCode(), status) || Objects.equals(PaymentStatusEnum.PARTIAL_RECEIPTS.getCode(), status));
                            if (!paymentSheetPer) {
                                continue;
                            }
                        }
                    }
                    boolean isInvoice = Objects.equals(status,PaymentStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(status,PaymentStatusEnum.RECEIVABLES.getCode()) || Objects.equals(status,PaymentStatusEnum.PARTIAL_RECEIPTS.getCode());
                    boolean notItemInputInvoice = invoiceAmount < paymentAmount && isInvoice && contractOrPurchaseCanInvoice;
                    boolean invoiceModelFlag = fundSetHelp.checkInvoiceModelFlag(modelType, nowMmodelType);
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_INVOICE)) {
                        if (!notItemInputInvoice || invoiceModelFlag) {
                            continue;
                        }
                    }
                    if (Objects.equals(status, PaymentStatusEnum.RECEIVABLES.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_RED)) {
                        continue;
                    }

                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case INVOICE:
                /*
                 * 正常发票：编辑、作废、红冲、删除；
                 * 作废发票：还原、删除；
                 * 红冲发票：删除；
                 */
                Integer isCancel = getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.IS_CANCEL.getAttr(), BasicConstant.ZERO);
                Integer isInvoiceRed = getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.IS_RED.getAttr(), BasicConstant.ZERO);
                Integer hasRed = getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.HAS_RED.getAttr(), BasicConstant.ZERO);
                //关联客户
                String linkCustomer = dataList.getString(InvoiceEnum.CUSTOMER_NAME.getAttr());
                //关联合同
                String linkContract = dataList.getString(InvoiceEnum.CONTRACT_ID.getAttr());
                //获得在什么模式下创建的发票
                Long invoiceModelType = paasFormDataEntityExt.getSysLong10();
                Double invoiceMoney = 0D;
                Double redTotalMoney = 0D;
                if (Objects.equals(hasRed, BasicConstant.ONE)) {
                    invoiceMoney = getDoubleOrDefaultFromFormData(dataList, InvoiceEnum.TOTAL_MONEY.getAttr(), BasicConstant.ZERO_DOUBLE);
                    redTotalMoney = invoiceModel.getRedTotalMoney(paasFormDataEntityExt.getId(), paasFormDataEntityExt.getCorpid());
                }
                /*if (Objects.equals(isInvoiceRed, 1)) {
                    topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }*/

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(isCancel, BasicConstant.ONE)) {
                        topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                        if (!Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_REVERT)) {
                            continue;
                        }
                    } else if (Objects.equals(isInvoiceRed, BasicConstant.ONE)) {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_CANCEL) || Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_RED) || Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_REVERT)) {
                            continue;
                        }
                    } else if (Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_LINK_CONTRACT)) {
                        //关联合同按钮判断
                        //.在①手动创建应收、③按出库产生应收模式下，允许对未关联过合同的发票进行关联，
                        //规则：a.发票已关联客户，但未关联任何合同 b.发票本身非红冲 c.非作废发票 d.未被红冲过          新添加关联合同按钮
                        boolean contractLinkButtonFlag = !Objects.equals(nowModelType, ModelTypeEnum.INVOICE.getCode()) && !Objects.equals(invoiceModelType, ModelTypeEnum.INVOICE.getCode()) && Objects.equals(isCancel, BasicConstant.ZERO)
                                && Objects.equals(isInvoiceRed, BasicConstant.ZERO) && Objects.equals(hasRed, BasicConstant.ZERO) && Objects.nonNull(linkCustomer) && Objects.isNull(linkContract);
                        if (!contractLinkButtonFlag) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_REVERT)) {
                            continue;
                        }
                        if (Objects.equals(hasRed, BasicConstant.ONE)) {
                            if (Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_CANCEL)) {
                                continue;
                            }
                            if (redTotalMoney + invoiceMoney <= 0 && Objects.equals(workFlowEnum, WorkFlowEnum.INVOICE_RED)) {
                                continue;
                            }
                        }
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                if (Objects.equals(hasRed,BasicConstant.ONE)) {
                    topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }
                break;
            case PURCHASE_INVOICE:
                /*
                 * 正常发票：编辑、作废、红冲、删除；
                 * 作废发票：还原、删除；
                 * 红冲发票：删除；
                 */
                Integer purchaseIsCancel = getIntegerOrDefaultFromFormData(dataList,PurchaseInvoiceEnum.IS_CANCEL.getAttr(), BasicConstant.ZERO);
                Integer isPurchaseInvoiceRed = getIntegerOrDefaultFromFormData(dataList,PurchaseInvoiceEnum.IS_RED.getAttr(), BasicConstant.ZERO);
                Integer hasPurchaseInvoiceRed = getIntegerOrDefaultFromFormData(dataList,PurchaseInvoiceEnum.HAS_RED.getAttr(), BasicConstant.ZERO);
                Double purchaseInvoiceMoney = 0D;
                Double purchaseInvoiceRedTotalMoney = 0D;
                if (Objects.equals(hasPurchaseInvoiceRed, BasicConstant.ONE)) {
                    purchaseInvoiceMoney = getDoubleOrDefaultFromFormData(dataList,PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(), BasicConstant.ZERO_DOUBLE);
                    purchaseInvoiceRedTotalMoney = purchaseInvoiceModel.getRedTotalMoney(paasFormDataEntityExt.getId(), paasFormDataEntityExt.getCorpid());
                }
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(purchaseIsCancel, BasicConstant.ONE)) {
                        topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                        if (!Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE_REVERT)) {
                            continue;
                        }
                    } else if (Objects.equals(isPurchaseInvoiceRed, BasicConstant.ONE)) {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE_CANCEL) || Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE_RED) || Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE_REVERT)) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE_REVERT)) {
                            continue;
                        }
                        if (Objects.equals(hasPurchaseInvoiceRed, BasicConstant.ONE)) {
                            if (Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE_CANCEL)) {
                                continue;
                            }
                            if (purchaseInvoiceRedTotalMoney + purchaseInvoiceMoney <= 0 && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE_RED)) {
                                continue;
                            }
                        }
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                if (Objects.equals(hasPurchaseInvoiceRed,BasicConstant.ONE)) {
                    topPermissions.removeIf(topPermissionsPoJo -> Objects.equals(topPermissionsPoJo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }
                break;
            case PURCHASE:
                // 采购合同已经入库完毕 则不显示‘生成入库单’按钮
                Double purchaseAmount = getDoubleOrDefaultFromFormData(dataList, PurchaseEnum.TOTAL_MONEY.getAttr(), BasicConstant.ZERO_DOUBLE);
                Double purchaseUnFinishAmount = getDoubleOrDefaultFromFormData(dataList, PurchaseEnum.UN_FINISH_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                supplierId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, PurchaseEnum.SUPPLIER_ID.getAttr(), BasicConstant.ZERO_LONG);
                param.put("purchaseId",paasFormDataEntityExt.getId());
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntityList = purchaseInvoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntityList)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntityList) {
                        invoiceAmount = Arith.add(invoiceAmount, purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
                Integer allIncoming = getIntegerOrDefaultFromFormData(dataList, PurchaseEnum.ALL_INCOMING.getAttr(), BasicConstant.ZERO);
                String receiveStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PurchaseEnum.RECEIVE_STATUS.getAttr(), ReceiveStatusEnum.UNRECEIVED.getCode());
                JSONArray instockArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PurchaseEnum.INSTOCK_ID.getAttr(), new JSONArray());
                Integer returnedPurchaseId = getIntegerOrDefaultFromFormData(dataList, PurchaseEnum.RETURNED_PURCHASE_ID.getAttr(), BasicConstant.ZERO);
                payBalanceEntity = payBalanceModel.getBySupplierId(supplierId,loginUser.getCorpid());
                isPayBalanceAmountExist = false;
                if(payBalanceEntity != null && payBalanceEntity.getAdvancePayBalance() > 0){
                    isPayBalanceAmountExist = true;
                }
                prepayMenu = paasMenuModel.getByAlias(XbbRefTypeEnum.PREPAY_BALANCE.getAlias(), corpid);
                //true预付款开启
                prePayFlag = prepayMenu != null && Objects.equals(prepayMenu.getEnable(), BasicConstant.ONE);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {

                    List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
                    if (esignHelp.addEsignWorkFlow(loginUserPermSet, workFlowPojoList, workFlowEnum,
                            XbbRefTypeEnum.PURCHASE, paasFormDataEntityExt)) {
                        if (workFlowPojoList.isEmpty()) {
                            continue;
                        }
                    }

                    if (Objects.equals(allIncoming, 1) && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INSTOCK)) {
                        continue;
                    }
                    if (Objects.equals(receiveStatus, ReceiveStatusEnum.CLOSED.getCode())&& Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INSTOCK)) {
                        continue;
                    }
                    // 采购合同未入库或者已经生成退货单 则不显示‘生成采购退货单’按钮
                    boolean noReturn = (instockArray.isEmpty() || returnedPurchaseId > 0) && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_RETURNED);
                    if (noReturn) {
                        continue;
                    }
                    if (invoiceAmount >= purchaseAmount && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE)) {
                        continue;
                    }
                    if ( Objects.equals(workFlowEnum, WorkFlowEnum.PURCAHASE_WRITE_OFF_PREPAY) && !prePayFlag) {
                        continue;
                    }
                    if ( purchaseUnFinishAmount <= 0D && (Objects.equals(workFlowEnum, WorkFlowEnum.PURCAHASE_WRITE_OFF_PREPAY) || Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_PAY_SHEET) || Objects.equals(workFlowEnum, WorkFlowEnum.PURCAHASE_PAY_SHEET_BAD))) {
                        continue;
                    }
                    if(!isPayBalanceAmountExist && Objects.equals(workFlowEnum, WorkFlowEnum.PURCAHASE_WRITE_OFF_PREPAY)){
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case RETURNED_PURCHASE:
                // 采购退货单已经生成过出库单 则不显示‘生成出库单’按钮
                Integer outstockId = getIntegerOrDefaultFromFormData(dataList, ReturnedPurchaseEnum.OUTSTOCK_ID.getAttr(), BasicConstant.ZERO);
                String returnedStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ReturnedPurchaseEnum.RETURNED_STATUS.getAttr(), ReturnedStatusEnum.UNRETURNED.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (outstockId > 0 && Objects.equals(workFlowEnum, WorkFlowEnum.RETURNED_PURCHASE_OUTSTOCK)) {
                        continue;
                    }
                    if (Objects.equals(returnedStatus,ReturnedStatusEnum.CLOSED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.RETURNED_PURCHASE_OUTSTOCK)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case INVENTORY:
                Integer inventoryInstockId = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.INSTOCK_ID.getAttr(), BasicConstant.ZERO);
                Integer ifProfit = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.IF_PROFIT.getAttr(), BasicConstant.ZERO);Integer inventoryOutstockId = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.OUTSTOCK_ID.getAttr(), BasicConstant.ZERO);
                Integer ifLoss = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.IF_LOSS.getAttr(), BasicConstant.ZERO);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    // 盘点单没有盘盈或者已经生成过入库单 则不显示‘生成入库单’按钮
                    boolean noInstock = (Objects.equals(ifProfit, 0) || inventoryInstockId > 0) && Objects.equals(workFlowEnum, WorkFlowEnum.INVENTORY_INSTOCK);
                    if (noInstock) {
                        continue;
                    }
                    // 盘点单没有盘亏或者已经生成过出库单 则不显示‘生成出库单’按钮
                    boolean noOutstock = (Objects.equals(ifLoss, 0) || inventoryOutstockId > 0) && Objects.equals(workFlowEnum, WorkFlowEnum.INVENTORY_OUTSTOCK);
                    if (noOutstock) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case TRANSFER:
                // 调拨单已经生成过出库单 则不显示‘生成出库单’按钮
                Integer transferOutstockId = getIntegerOrDefaultFromFormData(dataList, TransferEnum.OUTSTOCK_ID.getAttr(), BasicConstant.ZERO);
                Integer transferInstockId = getIntegerOrDefaultFromFormData(dataList, TransferEnum.INSTOCK_ID.getAttr(), BasicConstant.ZERO);
                String transferStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, TransferEnum.TRANSFER_STATUS.getAttr(), TransferNewStatusEnum.UNTRANSFORMED.getCode());
                Integer allBound = getIntegerFromFormData(dataList, TransferEnum.ALL_IN_BOUND.getAttr());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (transferOutstockId > 0 && Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_OUTSTOCK)) {
                        continue;
                    }
                    if (Objects.equals(transferStatus,TransferNewStatusEnum.CLOSED.getCode()) && (Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_OUTSTOCK)||Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_INSTOCK))) {
                        continue;
                    }
                    // 调拨单没有生成过出库单或者全部入库完毕 则不显示‘生成入库单’按钮
                    // 老数据出入库完毕也没有标识
                    boolean isOldInAllBound = transferInstockId > 0 && transferOutstockId > 0 && Objects.isNull(allBound);
                    boolean noTransferInstock = (Objects.equals(transferOutstockId, 0) || (Objects.nonNull(allBound) && allBound > 0) || isOldInAllBound) && Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_INSTOCK);
                    if (noTransferInstock) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case PRODUCTIONORDER:
                // 成品入库完毕 则不显示‘新建成品入库’按钮
                /*Integer orderAllIncoming = saasUpdateHelp.getIntegerOrDefaultFromFormData(dataList, ProductionOrderEnum.ALL_INCOMING.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(orderAllIncoming, 1) && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_PRODUCT_INSTOCK)) {
                    continue;
                }
                // 物料出库完毕 则不显示‘新建物料出库’按钮
                Integer orderAllOutbound = saasUpdateHelp.getIntegerOrDefaultFromFormData(dataList, ProductionOrderEnum.ALL_OUTBOUND.getAttr(), BasicConstant.ZERO);

                if (Objects.equals(orderAllOutbound, 1) && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_OUTSTOCK)) {
                    continue;
                }
                // 没有退料可以入库 则不显示‘退料入库’按钮
                Integer hasReturnedMateriel = saasUpdateHelp.getIntegerOrDefaultFromFormData(dataList, ProductionOrderEnum.HAS_RETURNED_MATERIEL.getAttr(), BasicConstant.ZERO);
                if (!Objects.equals(hasReturnedMateriel, 1) && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_INSTOCK)) {
                    continue;
                }*/
                Integer productionOrderStatus = getIntegerOrDefaultFromFormData(dataList, ProductionOrderEnum.STATUS.getAttr(), BasicConstant.ZERO);
                // 获取成品未入库数量
                Double alreadyUnInstockNum = getDoubleOrDefaultFromFormData(dataList, ProductionOrderEnum.PRODUCT_UNINSTOCK_NUM.getAttr(), 0.0D);
                ProductionOrderEntityExt productionOrderEntityExt = new ProductionOrderEntityExt();
                BeanUtil.copyProperties(paasFormDataEntityExt, productionOrderEntityExt);
                boolean hasReturnedInstock = productionOrderService.hasReturnedMaterielInstock(productionOrderEntityExt);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(ProductionOrderStatusEnum.UNFINISHED.getCode(), productionOrderStatus)) {
                        if (!hasReturnedInstock && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_INSTOCK)) {
                            continue;
                        }
//                        // 暂时处理未入库数量为0并且未完成的生产单(不允许成品入库)
//                        if (!Arith.comperaTwoDoubleByAccuracy(alreadyUnInstockNum, 0.0D, 2) && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_PRODUCT_INSTOCK)) {
//                            continue;
//                        }
                    } else if (Objects.equals(ProductionOrderStatusEnum.CLOSED.getCode(), productionOrderStatus)) {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_OUTSTOCK)) {
                            continue;
                        }
                        if (!hasReturnedInstock && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_INSTOCK)) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_OUTSTOCK)
                                || Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_INSTOCK)
                                || Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_PRODUCT_INSTOCK)) {
                            continue;
                        }
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case BOMBILL:
                Integer isDefault = getIntegerOrDefaultFromFormData(dataList, BomBillEnum.VERSION_LINK_TEXT.getAttr(), BasicConstant.ZERO);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(isDefault, BasicConstant.ONE) && Objects.equals(workFlowEnum, WorkFlowEnum.BOM_BILL_SET_DEFAULT_VERSION)) {
                        continue;
                    }
                    if (Objects.equals(isDefault, BasicConstant.ZERO) && Objects.equals(workFlowEnum, WorkFlowEnum.BOM_BILL_UN_SET_DEFAULT_VERSION)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case REFUND:
                if (Objects.isNull(dataList)) {
                    break;
                }
                String refundStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, RefundEnum.REFUND_STATUS.getAttr(), RefundStatusEnum.UNREFUND.getCode());
                Integer allInStock = getIntegerOrDefaultFromFormData(dataList, RefundEnum.ALL_IN_BOUND.getAttr(), BasicConstant.ONE);
                // 只有0:部分(未)入库时才展示按钮
                boolean isInStock = Objects.equals(allInStock, BasicConstant.ONE) || Objects.equals(allInStock, BasicConstant.TWO);
                boolean isOpened = Objects.equals(refundStatus, RefundStatusEnum.CLOSED.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (isInStock && Objects.equals(workFlowEnum, WorkFlowEnum.REFUND_INSTOCK)) {
                        continue;
                    }
                    if (isOpened && Objects.equals(workFlowEnum, WorkFlowEnum.REFUND_INSTOCK)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                // 未确认: 提醒确认  代客确认  重新生成
                // 已确认: 重新生成  归档
                // 待处理: 重新生成
                // 已归档: 取消归档
                workFlowEnumList.clear();
                String statementStatus = dataList.getString(CustomerStatementStatisticDistributorEnum.STATUS.getAttr());
                int statementArchive = dataList.getIntValue(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr());
                if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    if (Objects.equals(statementArchive, ArchivedEnum.UN_ARCHIVED.getCode())) {
                        if (Objects.equals(statementStatus, CustomerStatementStatusEnum.UNCONFIRMED.getCode())) {
                            workFlowEnumList.add(WorkFlowEnum.REMIND_CONFIRM_STATEMENT);
                            workFlowEnumList.add(WorkFlowEnum.VALET_CONFIRM_STATEMENT);
                        } else if (Objects.equals(statementStatus, CustomerStatementStatusEnum.CONFIRMED.getCode())) {
                            workFlowEnumList.add(WorkFlowEnum.ARCHIVE_STATEMENT);
                        }
                        workFlowEnumList.add(WorkFlowEnum.REGENERATE_STATEMENT);
                    } else if (Objects.equals(statementArchive, ArchivedEnum.ARCHIVED.getCode())) {
                        workFlowEnumList.add(WorkFlowEnum.CANCEL_ARCHIVE_STATEMENT);
                    }
                } else {
                    if (Objects.equals(statementArchive, ArchivedEnum.UN_ARCHIVED.getCode())) {
                        workFlowEnumList.add(WorkFlowEnum.ARCHIVE_STATEMENT);
                    } else if (Objects.equals(statementArchive, ArchivedEnum.ARCHIVED.getCode())) {
                        workFlowEnumList.add(WorkFlowEnum.CANCEL_ARCHIVE_STATEMENT);
                    }
                }
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case QUOTATION:
                Integer quotationArchived = getIntegerOrDefaultFromFormData(dataList, QuotationEnum.ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                Integer isNew = getIntegerOrDefaultFromFormData(dataList, QuotationEnum.IS_NEW.getAttr(), BasicConstant.ONE);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {

                    List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
                    if (esignHelp.addEsignWorkFlow(loginUserPermSet, workFlowPojoList, workFlowEnum,
                            XbbRefTypeEnum.QUOTATION, paasFormDataEntityExt)) {
                        if (workFlowPojoList.isEmpty()) {
                            continue;
                        }
                    }

                    if (!hasUpdate && (Objects.equals(workFlowEnum, WorkFlowEnum.QUOTATION_ARCHIVED) || Objects.equals(workFlowEnum, WorkFlowEnum.QUOTATION_CANCEL_ARCHIVED))) {
                        continue;
                    }
                    if (Objects.equals(quotationArchived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.QUOTATION_ARCHIVED)) {
                        continue;
                    }
                    if (Objects.equals(quotationArchived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.QUOTATION_CANCEL_ARCHIVED)) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                if (!Objects.equals(isNew, BasicConstant.ONE)) {
                    // 不是最新版本的报价单不能编辑
                    topPermissions.removeIf(item -> Objects.equals(item.getAttr(), OperateTypeEnum.EDIT.getAlias()));
                }
                break;
            case PAYMENT_SHEET:
                Double paymentSheetAmount = getDoubleOrDefaultFromFormData(dataList, PaymentSheetEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                List<PaasFormDataEntityExt> paasFormDataEntityExtList = fundHelp.getChildEsDataListByParentUuid(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET,corpid,paasFormDataEntityExt.getUuid(),null);
                if(!Objects.equals(paasFormDataEntityExt.getAlone(), SheetAloneEnum.NORMAL.getCode())) {
                    if (CollectionsUtil.isNotEmpty(paasFormDataEntityExtList)) {
                        for (PaasFormDataEntityExt paasFormData : paasFormDataEntityExtList) {
                            subIdList.add(paasFormData.getId());
                        }
                    }
                }else {
                    subIdList.add(paasFormDataEntityExt.getId());
                }
                param.put("paymentSheetIdIn",subIdList);
                List<InvoiceRelationshipEntity> invoiceRelationship = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(invoiceRelationship)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationship) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                //回款单类型
                String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.WRITE_OFF.getCode());
                //核销，预收款核销才有红冲按钮
                boolean redButtonFlag = Objects.equals(paymentSheetType, PaymentSheetTypeEnum.WRITE_OFF.getCode()) || Objects.equals(paymentSheetType, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT.getCode());
                Integer sheetBusinessType = PaymentSheetTypeEnum.getBusinessTypeByCode(paymentSheetType);
                for (TopPermissionsPoJo topPermission : topPermissions) {
                    //回款单编辑、删除按钮，要基于回款单类型得到businessType：因为回款单详情打开前端拿到的都是702，而要根据回款单data内的paymentSheetType确定具体是哪种类型回款单
                    topPermission.setBusinessType(sheetBusinessType);
                    topPermission.setDistributorMark(distributorMark);
                }
                Set<String> permSet = loginUser.getPermSet();
                boolean redButtonPermision = false;
                if (!ObjectUtils.isEmpty(permSet)) {
                    redButtonPermision = permSet.contains(WorkFlowEnum.PAYMENT_SHEET_RED.getPermission());
                }
                if (redButtonFlag && redButtonPermision) {
                    //true 已红冲金额超过了回款单的回款金额/核销金额，无红冲按钮；false 未超过
                    boolean redOver = proDetailHandlerHelp.checkRedOver(XbbRefTypeEnum.PAYMENT_SHEET, paasFormDataEntityExt.getId(), dataList, paasFormDataEntityExt.getCorpid(), paymentSheetType);
                    if (!redOver) {
                        addRedButton(distributorMark, topPermissions, paasBusinessTypeToName, paymentSheetType);
                    }
                }
                boolean invoiceModelFlag = fundSetHelp.checkInvoiceModelFlag(modelType, nowMmodelType);
                //非开票模式，且已核销、预收款才有新建发票按钮
                boolean invoiceFlow = !invoiceModelFlag && invoiceAmount < paymentSheetAmount && SheetTypeEnum.ifNewInvoice(paymentSheetType) && permSet.contains(WorkFlowEnum.PAYMENT_SHEET_INVOICE.getPermission()) && contractOrPurchaseCanInvoice;
                if (invoiceFlow) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(WorkFlowEnum.PAYMENT_SHEET_INVOICE, topPermissionsPoJo);
                    if (Objects.equals(WorkFlowEnum.PAYMENT_SHEET_INVOICE.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case PAY_SHEET:
                Double paySheetAmount = getDoubleOrDefaultFromFormData(dataList, PaySheetEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                List<PaasFormDataEntityExt> paasFormDataExtList = fundHelp.getChildEsDataListByParentUuid(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET,corpid,paasFormDataEntityExt.getUuid(),null);
                if(!Objects.equals(paasFormDataEntityExt.getAlone(), SheetAloneEnum.NORMAL.getCode())) {
                    if (CollectionsUtil.isNotEmpty(paasFormDataExtList)) {
                        for (PaasFormDataEntityExt paasFormData : paasFormDataExtList) {
                            subIdList.add(paasFormData.getId());
                        }
                    }
                }else {
                    subIdList.add(paasFormDataEntityExt.getId());
                }
                param.put("paySheetIdIn",subIdList);
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationship = purchaseInvoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationship)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationship) {
                        invoiceAmount = Arith.add(invoiceAmount, purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
                //付款单类型
                String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                //核销，预付款核销才有红冲按钮
                redButtonFlag = Objects.equals(paySheetType, PaySheetTypeEnum.WRITE_OFF_PAY.getCode()) || Objects.equals(paySheetType, PaySheetTypeEnum.WRITE_OFF_PREPAY.getCode());
                sheetBusinessType = PaySheetTypeEnum.getBusinessTypeByCode(paySheetType);
                for (TopPermissionsPoJo topPermission : topPermissions) {
                    //付款单编辑、删除按钮，要基于付款单类型得到businessType：因为付款单详情打开前端拿到的都是802，而要根据付款单data内的paySheetType确定具体是哪种类型付款单
                    topPermission.setBusinessType(sheetBusinessType);
                }
                //还要判断登录者是否有红冲按钮权限 FXI wangtengwei 2020/05/16
                Set<String> permSetSen = loginUser.getPermSet();
                boolean redButtonPermisionSen = false;
                if (!ObjectUtils.isEmpty(permSetSen)) {
                    redButtonPermisionSen = permSetSen.contains(WorkFlowEnum.PAY_SHEET_RED.getPermission());
                }
                if (redButtonFlag && redButtonPermisionSen) {
                    //true 已红冲金额超过了付款单的付款金额/核销金额，无红冲按钮；false 未超过
                    boolean redOver = proDetailHandlerHelp.checkRedOver(XbbRefTypeEnum.PAY_SHEET, paasFormDataEntityExt.getId(), dataList, paasFormDataEntityExt.getCorpid(), paySheetType);
                    if (!redOver) {
                        Integer redBusinessType = PaySheetTypeEnum.getRedBusinessTypeByCode(paySheetType);
                        TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                        BeanUtil.copyProperties(WorkFlowEnum.PAY_SHEET_RED, topPermissionsPoJo);
                        if (Objects.equals(WorkFlowEnum.PAY_SHEET_RED.getFormRelation(), BasicConstant.ONE)) {
                            changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                        }
                        //付款单的红冲按钮的businessType要基于付款单类型来动态设置（比如不同类型付款单的详情，要置为不同的）
                        topPermissionsPoJo.setBusinessType(redBusinessType);
                        topPermissions.add(topPermissionsPoJo);
                    }
                }
                //已核销，预付款才有新建发票按钮
                invoiceFlow = invoiceAmount < paySheetAmount && SheetTypeEnum.ifNewInvoice(paySheetType) && permSetSen.contains(WorkFlowEnum.PAY_SHEET_INVOICE.getPermission()) && contractOrPurchaseCanInvoice;
                if (invoiceFlow) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(WorkFlowEnum.PAY_SHEET_INVOICE, topPermissionsPoJo);
                    if (Objects.equals(WorkFlowEnum.PAY_SHEET_INVOICE.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case WORKORDER:
                // 工单的topPermissions比较特殊在上面处理了，此处不处理
                break;
            case PAYMENT_TASK:
                break;
            case CREDIT_LIMIT:
                // 冻结解冻
                String creditStatus = FastJsonHelper.getStringFromFormData(dataList, CreditLimitEnum.STATUS.getAttr());
                TopPermissionsPoJo freezePermission = new TopPermissionsPoJo();
                if (Objects.equals(creditStatus, CreditLimitStatusEnum.NORMAL.getCode())) {
                    // 申请临额度、申请固定额度
                    for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                        TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                        BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                        if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                            changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                        }
                        topPermissionsPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(workFlowEnum.getBusinessType()));
                        topPermissionsPoJo.setDistributorMark(distributorMark);
                        topPermissions.add(topPermissionsPoJo);
                    }
                    freezePermission.setAttr(ListOptionTabEnum.CREDIT_FREEZE.getAttr());
                    freezePermission.setValue(ListOptionTabEnum.CREDIT_FREEZE.getAttrName());
                } else {
                    freezePermission.setAttr(ListOptionTabEnum.CREDIT_UNFREEZE.getAttr());
                    freezePermission.setValue(ListOptionTabEnum.CREDIT_UNFREEZE.getAttrName());
                }
                freezePermission.setBtnType("set");
                freezePermission.setBusinessType(XbbRefTypeEnum.CREDIT_LIMIT.getCode());
                freezePermission.setDistributorMark(distributorMark);
                topPermissions.add(freezePermission);
                break;
            case CREDIT_TEMPORARY_LIMIT:
                // 撤销
                String temporaryStatus = FastJsonHelper.getStringFromFormData(dataList, CreditTemporaryLimitEnum.APPLY_STATUS.getAttr());
                int endTime = dataList.getIntValue(CreditTemporaryLimitEnum.END_TIME.getAttr());
                if (endTime >= DateTimeUtil.getTodayInt() && Objects.equals(temporaryStatus, CreditTemporaryApplyStatusEnum.NORMAL.getCode())) {
                    TopPermissionsPoJo revokePermission = new TopPermissionsPoJo();
                    revokePermission.setAttr(ListOptionTabEnum.CREDIT_REVOKE.getAttr());
                    revokePermission.setValue(ListOptionTabEnum.CREDIT_REVOKE.getAttrName());
                    revokePermission.setBtnType("set");
                    revokePermission.setBusinessType(XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode());
                    revokePermission.setDistributorMark(distributorMark);
                    topPermissions.add(revokePermission);
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.DISTRIBUTOR_PAYMENT) && !Objects.equals(nowMmodelType, ModelTypeEnum.PLAN.getCode())) {
                        continue;
                    }
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(workFlowEnum.getBusinessType()));
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case OTHER_INCOME:
                //其他收入单类型
                String otherIncomeSheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), OtherIncomeEnum.SHEET_TYPE_OTHER.getAttr(), OtherIncomeSheetTypeEnum.OTHER_INCOME.getCode());
                //已收款才有红冲按钮
                redButtonFlag = Objects.equals(otherIncomeSheetType, OtherIncomeSheetTypeEnum.OTHER_INCOME.getCode());
                sheetBusinessType = OtherIncomeSheetTypeEnum.getBusinessTypeByCode(otherIncomeSheetType);
                for (TopPermissionsPoJo topPermission : topPermissions) {
                    //收入单编辑按钮，要基于收入单类型得到businessType：因为收入单详情打开前端拿到的都是5710，而要根据收入单data内的sheetType确定具体是哪种类型收入单
                    topPermission.setBusinessType(sheetBusinessType);
                }
                Set<String> permSetOtherIncome = loginUser.getPermSet();
                redButtonPermision = false;
                if (!ObjectUtils.isEmpty(permSetOtherIncome)) {
                    redButtonPermision = permSetOtherIncome.contains(WorkFlowEnum.OTHER_INCOME_RED.getPermission());
                }
                if (redButtonFlag && redButtonPermision) {
                    //true 已红冲金额超过了其他收入单的金额，无红冲按钮；false 未超过
                    boolean redOver = proDetailHandlerHelp.checkRedOver(XbbRefTypeEnum.OTHER_INCOME, paasFormDataEntityExt.getId(), dataList, paasFormDataEntityExt.getCorpid(), otherIncomeSheetType);
                    if (!redOver) {
                        Integer redBusinessType = OtherIncomeSheetTypeEnum.getRedBusinessTypeByCode(otherIncomeSheetType);
                        TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                        BeanUtil.copyProperties(WorkFlowEnum.OTHER_INCOME_RED, topPermissionsPoJo);
                        if (Objects.equals(WorkFlowEnum.OTHER_INCOME_RED.getFormRelation(), BasicConstant.ONE)) {
                            changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                        }
                        //红冲按钮的businessType要基于其他收入单类型来动态设置（比如不同类型收入单的详情，要置为不同的对应红冲类型）
                        topPermissionsPoJo.setBusinessType(redBusinessType);
                        topPermissions.add(topPermissionsPoJo);
                    }
                }
                break;
            case OTHER_EXPENSE:
                //其他支出单类型
                String otherExpenseSheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), OtherExpenseEnum.SHEET_TYPE_OTHER.getAttr(), OtherExpenseSheetTypeEnum.OTHER_EXPENSE.getCode());
                //已付款才有红冲按钮
                redButtonFlag = Objects.equals(otherExpenseSheetType, OtherExpenseSheetTypeEnum.OTHER_EXPENSE.getCode());
                sheetBusinessType = OtherExpenseSheetTypeEnum.getBusinessTypeByCode(otherExpenseSheetType);
                for (TopPermissionsPoJo topPermission : topPermissions) {
                    //支出单编辑按钮，要基于支出单类型得到businessType：因为支出单详情打开前端拿到的都是5710，而要根据支出单data内的sheetType确定具体是哪种类型支出单
                    topPermission.setBusinessType(sheetBusinessType);
                }
                Set<String> permSetOtherExpense = loginUser.getPermSet();
                redButtonPermision = false;
                if (!ObjectUtils.isEmpty(permSetOtherExpense)) {
                    redButtonPermision = permSetOtherExpense.contains(WorkFlowEnum.OTHER_EXPENSE_RED.getPermission());
                }
                if (redButtonFlag && redButtonPermision) {
                    //true 已红冲金额超过了其他支出单的金额，无红冲按钮；false 未超过
                    boolean redOver = proDetailHandlerHelp.checkRedOver(XbbRefTypeEnum.OTHER_EXPENSE, paasFormDataEntityExt.getId(), dataList, paasFormDataEntityExt.getCorpid(), otherExpenseSheetType);
                    if (!redOver) {
                        Integer redBusinessType = OtherExpenseSheetTypeEnum.getRedBusinessTypeByCode(otherExpenseSheetType);
                        TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                        BeanUtil.copyProperties(WorkFlowEnum.OTHER_EXPENSE_RED, topPermissionsPoJo);
                        if (Objects.equals(WorkFlowEnum.OTHER_EXPENSE_RED.getFormRelation(), BasicConstant.ONE)) {
                            changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                        }
                        //红冲按钮的businessType要基于其他支出单类型来动态设置（比如不同类型支出单的详情，要置为不同的对应红冲类型）
                        topPermissionsPoJo.setBusinessType(redBusinessType);
                        topPermissions.add(topPermissionsPoJo);
                    }
                }
                break;
            case FUND_TRANSFER:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    topPermissions.add(topPermissionsPoJo);
                }
                topPermissions.removeIf(pojo-> Objects.equals(pojo.getAttr(), OperateTypeEnum.DELETE.getAlias()));
                break;
            default:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                        changeValue(paasBusinessTypeToName, topPermissionsPoJo);
                    }
                    topPermissionsPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(workFlowEnum.getBusinessType()));
                    topPermissionsPoJo.setDistributorMark(distributorMark);
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
        }
    }

    /**
     * 增加红冲按钮
     * @param distributorMark
     * @param topPermissions
     * @param paasBusinessTypeToName
     * @param paymentSheetType
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void addRedButton(Integer distributorMark, List<TopPermissionsPoJo> topPermissions, Map<Integer, String> paasBusinessTypeToName, String paymentSheetType) {
        boolean writeOffFlag = SheetTypeEnum.checkWriteOffPrepayment(paymentSheetType);
        Integer redBusinessType = PaymentSheetTypeEnum.getRedBusinessTypeByCode(paymentSheetType);
        TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
        BeanUtil.copyProperties(WorkFlowEnum.PAYMENT_SHEET_RED, topPermissionsPoJo);
        if (Objects.equals(WorkFlowEnum.PAYMENT_SHEET_RED.getFormRelation(), BasicConstant.ONE)) {
            changeValue(paasBusinessTypeToName, topPermissionsPoJo);
        }
        //回款单的红冲按钮的businessType要基于回款单类型来动态设置（比如不同类型回款单的详情，要置为不同的）
        topPermissionsPoJo.setBusinessType(redBusinessType);
        topPermissionsPoJo.setDistributorMark(distributorMark);
        topPermissions.add(topPermissionsPoJo);
        if (writeOffFlag) {
            //再添加红冲(退到余额)按钮
            TopPermissionsPoJo topPermissionsPoJoRed = new TopPermissionsPoJo();
            BeanUtil.copyProperties(WorkFlowEnum.PAYMENT_SHEET_RED_BALANCE, topPermissionsPoJoRed);
            if (Objects.equals(WorkFlowEnum.PAYMENT_SHEET_RED_BALANCE.getFormRelation(), BasicConstant.ONE)) {
                changeValue(paasBusinessTypeToName, topPermissionsPoJoRed);
            }
            //回款单的红冲按钮的businessType要基于回款单类型来动态设置（比如不同类型回款单的详情，要置为不同的）
            topPermissionsPoJoRed.setBusinessType(WorkFlowEnum.PAYMENT_SHEET_RED_BALANCE.getBusinessType());
            topPermissionsPoJoRed.setDistributorMark(distributorMark);
            topPermissions.add(topPermissionsPoJoRed);
        }
    }

    private void changeValue(Map<Integer, String> paasBusinessTypeToName, TopPermissionsPoJo topPermissionsPoJo) {
        StringBuilder newName = new StringBuilder();
        Integer pojoBusinessType = topPermissionsPoJo.getBusinessType();
        List<String> strings = Arrays.asList("new", "set");
        if (needToChangeName(paasBusinessTypeToName, pojoBusinessType) && strings.contains(topPermissionsPoJo.getBtnType())) {
            newName.append(topPermissionsPoJo.getValue().substring(0, 2)).append(paasBusinessTypeToName.get(pojoBusinessType));
            topPermissionsPoJo.setValue(newName.toString());
        }
    }

    private boolean needToChangeName(Map<Integer, String> paasBusinessTypeToName, Integer pojoBusinessType) {
        return !Objects.equals(XbbRefTypeEnum.getByCode(pojoBusinessType).getName(), paasBusinessTypeToName.get(pojoBusinessType)) && StringUtil.isNotEmpty(paasBusinessTypeToName.get(pojoBusinessType));
    }

    /**
     * 获取移动端详情基础信息右侧显示的状态
     *
     * @param sheetTypeEnum 回/付款单类型，如果不是回/付款单，可默认传null
     * @param businessType 业务类型
     * @param data         表单数据
     * @return MobileDetailStatusPojo
     * @author GuoJun.HU
     * @date 2019/3/13 11:10
     * @since V1.0
     * @update 2019/11/29 by zcp 增加回款单情况处理
     */
    private MobileDetailStatusPojo getDetailShowStatus(SheetTypeEnum sheetTypeEnum, Integer businessType, JSONObject data) throws XbbException {
        MobileDetailStatusPojo mobileDetailStatusPojo = new MobileDetailStatusPojo();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                Integer isArchived = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_ARCHIVED.getAttr(), 2);
                mobileDetailStatusPojo.setName("archived");
                mobileDetailStatusPojo.setValue(isArchived);
                break;
            case CONTRACT:
                Integer isRed = getIntegerOrDefaultFromFormData(data, ContractEnum.IS_RED.getAttr(), 0);
                if (Objects.equals(isRed, 1)) {
                    // 状态为红冲
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(isRed);
                }
                Integer hasRed = getIntegerOrDefaultFromFormData(data, ContractEnum.HAS_RED.getAttr(), 0);
                if (Objects.equals(hasRed, 1)) {
                    // 状态为已退款
                    mobileDetailStatusPojo.setName("hasRed");
                    mobileDetailStatusPojo.setValue(hasRed);
                }
                Integer contractArchived = getIntegerOrDefaultFromFormData(data, ContractEnum.ARCHIVED.getAttr(), 2);
                mobileDetailStatusPojo.setName("archived");
                mobileDetailStatusPojo.setValue(contractArchived);
                break;
            case INVOICE:
                Integer isCancel = getIntegerOrDefaultFromFormData(data, InvoiceEnum.IS_CANCEL.getAttr(), 0);
                if (Objects.equals(isCancel, 1)) {
                    // 状态为作废
                    mobileDetailStatusPojo.setName("isCancel");
                    mobileDetailStatusPojo.setValue(isCancel);
                }
                /*Integer invoiceHasRed = saasUpdateHelp.getIntegerOrDefaultFromFormData(data, InvoiceEnum.HAS_RED.getAttr(), 0);
                if (Objects.equals(invoiceHasRed, 1)) {
                    // 状态为已退款
                    mobileDetailStatusPojo.setName("hasRed");
                    mobileDetailStatusPojo.setValue(invoiceHasRed);
                }*/
                Integer invoiceIsRed = getIntegerOrDefaultFromFormData(data, InvoiceEnum.IS_RED.getAttr(), 0);
                if (Objects.equals(invoiceIsRed, 1)) {
                    // 状态为红冲
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(invoiceIsRed);
                }
                break;
            case PURCHASE_INVOICE:
                Integer purchaseInvoiceIsCancel = getIntegerOrDefaultFromFormData(data,PurchaseInvoiceEnum.IS_CANCEL.getAttr(), 0);
                if (Objects.equals(purchaseInvoiceIsCancel, 1)) {
                    // 状态为作废
                    mobileDetailStatusPojo.setName("isCancel");
                    mobileDetailStatusPojo.setValue(purchaseInvoiceIsCancel);
                }

                Integer purchaseInvoiceIsRed = getIntegerOrDefaultFromFormData(data, PurchaseInvoiceEnum.IS_RED.getAttr(), 0);
                if (Objects.equals(purchaseInvoiceIsRed, 1)) {
                    // 状态为红冲
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(purchaseInvoiceIsRed);
                }
                break;
            case PAYMENT:
                Integer paymentStatus = FastJsonHelper.getIntegerOrDefaultFromFormData(data, PaymentEnum.STATUS.getAttr(), 0);
                Integer paymentStatusIsRed = FastJsonHelper.getIntegerOrDefaultFromFormData(data, PaymentEnum.RECEIVABLE_IS_RED.getAttr(), 0);
                if (Objects.equals(paymentStatus.toString(), PaymentStatusEnum.BAD_DEBT.getCode())) {
                    mobileDetailStatusPojo.setName("allBad");
                    mobileDetailStatusPojo.setValue(paymentStatus);
                } else if (Objects.equals(paymentStatus.toString(), PaymentStatusEnum.PARTIAL_BAD_DEBT.getCode())) {
                    mobileDetailStatusPojo.setName("partBad");
                    mobileDetailStatusPojo.setValue(paymentStatus);
                } else if (Objects.equals(paymentStatusIsRed, 1)) {
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(paymentStatusIsRed);
                }
                break;
            case PAY_PLAN:
                Integer payPlanStatus = getIntegerOrDefaultFromFormData(data, PayPlanEnum.STATUS.getAttr(), 0);
                if (Objects.equals(payPlanStatus.toString(), PayPlanStatusEnum.BAD_DEBT.getCode())) {
                    mobileDetailStatusPojo.setName("allBad");
                    mobileDetailStatusPojo.setValue(payPlanStatus);
                } else if (Objects.equals(payPlanStatus.toString(), PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode())) {
                    mobileDetailStatusPojo.setName("partBad");
                    mobileDetailStatusPojo.setValue(payPlanStatus);
                }
                break;
            case SALES_OPPORTUNITY:
                Integer archived = getIntegerOrDefaultFromFormData(data, SalesOpportunityEnum.IS_ARCHIVED.getAttr(), 2);
                mobileDetailStatusPojo.setName("archived");
                mobileDetailStatusPojo.setValue(archived);
                break;
            case QUOTATION:
                Integer quotationArchived = getIntegerOrDefaultFromFormData(data, QuotationEnum.ARCHIVED.getAttr(), 2);
                mobileDetailStatusPojo.setName("archived");
                mobileDetailStatusPojo.setValue(quotationArchived);
                break;
            case PAYMENT_SHEET:
                if (sheetTypeEnum == null) {
                    break;
                }
                String paymentSheetType = sheetTypeEnum.getCode();
                boolean badFlag = PaymentSheetTypeEnum.isBad(paymentSheetType);
                boolean redFlag = PaymentSheetTypeEnum.isRed(paymentSheetType);
                if (badFlag) {
                    mobileDetailStatusPojo.setName("allBad");
                    mobileDetailStatusPojo.setValue(paymentSheetType);
                } else if (redFlag) {
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(paymentSheetType);
                }
                break;
            case PAY_SHEET:
                if (sheetTypeEnum == null) {
                    break;
                }
                String paySheetType = sheetTypeEnum.getCode();
                badFlag = PaySheetTypeEnum.isBad(paySheetType);
                redFlag = PaySheetTypeEnum.isRed(paySheetType);
                if (badFlag) {
                    mobileDetailStatusPojo.setName("allBad");
                    mobileDetailStatusPojo.setValue(paySheetType);
                } else if (redFlag) {
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(paySheetType);
                }
                break;
            case CLUE:
                Integer archivedFlag = getIntegerOrDefaultFromFormData(data, ClueEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                mobileDetailStatusPojo.setName("archived");
                mobileDetailStatusPojo.setValue(archivedFlag);
                break;
            case OTHER_INCOME:
                if (sheetTypeEnum == null) {
                    break;
                }
                String otherIncomeSheetType = sheetTypeEnum.getCode();
                redFlag = OtherIncomeSheetTypeEnum.isRed(otherIncomeSheetType);
                if (redFlag) {
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(otherIncomeSheetType);
                }
                break;
            case OTHER_EXPENSE:
                if (sheetTypeEnum == null) {
                    break;
                }
                String otherExpenseSheetType = sheetTypeEnum.getCode();
                redFlag = OtherExpenseSheetTypeEnum.isRed(otherExpenseSheetType);
                if (redFlag) {
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(otherExpenseSheetType);
                }
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                int archivedStatement = data.getIntValue(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr());
                mobileDetailStatusPojo.setName("archived");
                mobileDetailStatusPojo.setValue(archivedStatement);
                break;
            case ORDER:
                isRed = FastJsonHelper.getIntegerOrDefaultFromFormData(data, OrderEnum.IS_RED.getAttr(), 0);
                if (Objects.equals(isRed, 1)) {
                    // 状态为红冲
                    mobileDetailStatusPojo.setName("isRed");
                    mobileDetailStatusPojo.setValue(isRed);
                }
                hasRed = FastJsonHelper.getIntegerOrDefaultFromFormData(data, OrderEnum.HAS_RED.getAttr(), 0);
                if (Objects.equals(hasRed, 1)) {
                    // 状态为已退款
                    mobileDetailStatusPojo.setName("hasRed");
                    mobileDetailStatusPojo.setValue(hasRed);
                }
                contractArchived = FastJsonHelper.getIntegerOrDefaultFromFormData(data, OrderEnum.ARCHIVED.getAttr(), 2);
                mobileDetailStatusPojo.setName("archived");
                mobileDetailStatusPojo.setValue(contractArchived);
                break;
            default:
                break;
        }
        return mobileDetailStatusPojo;
    }

    /**
     * 获取移动端详情基础信息右上角显示的内容
     *
     * @param sheetTypeEnum 回/付款单类型，如果不是回/付款单，可默认传null
     * @param businessType 业务类型
     * @param loginUser
     * @param paasFormDataEntityExt
     * @param explainMap   解释
     * @return List
     * @author GuoJun.HU
     * @date 2019/3/13 11:10
     * @since V1.0
     * @update 2019/11/29 by zcp 增加回款单情况处理（回款单有7种类型，其中预收款核销的金额在核销金额字段内）
     */
    private List<MobileDetailScriptPojo> getDetailShowScript(SheetTypeEnum sheetTypeEnum, Integer businessType, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        List<MobileDetailScriptPojo> scriptPojoList = new ArrayList<>();
        String corpid = loginUser.getCorpid();
        Long dataId = paasFormDataEntityExt.getId();
        JSONObject data = paasFormDataEntityExt.getData();
        Integer flowStatus = paasFormDataEntityExt.getFlowStatus();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case SALES_OPPORTUNITY:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttr(), scriptPojoList);
                break;
            case PRODUCT:
                boolean stockCanSee = formDataValidateProductHelp.attrCanSee(explainMap.get(ProductEnum.STOCK.getAttr()),dataId,paasFormDataEntityExt.getCreatorId(),loginUser,corpid,XbbRefTypeEnum.PRODUCT.getCode());
                if (!stockCanSee){
                    break;
                }
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery("del",0));
                boolQueryBuilder.filter(termQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID),paasFormDataEntityExt.getId()));
                List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder,PaasFormDataEntityExt.class,Collections.singletonList(ProductEnum.getAttrConnectData(ProductEnum.STOCK)));
                Double stock = 0D;
                for (PaasFormDataEntityExt entityExt : paasFormDataEntityExtList){
                    stock = Arith.add(stock,entityExt.getData().getDouble(ProductEnum.STOCK.getAttr()));
                }

                String unit = FastJsonHelper.getStringOrDefaultFromFormData(data, ProductEnum.UNIT.getAttr(), "");
                FieldAttrEntity unitFieldAttr = explainMap.getOrDefault(ProductEnum.UNIT.getAttr(), new FieldAttrEntity());
                String unitStr = "";
                boolean enableMultiUnit = Objects.equals(data.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), BasicConstant.ONE);
                if (enableMultiUnit) {
                    Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
                    unitStr = groupBaseUnitMap.getOrDefault(Long.valueOf(unit), new MultiUnitItemPoJo()).getBaseName();
                }else if (unitFieldAttr != null && unitFieldAttr.getItems() != null) {
                    JSONObject json = new JSONObject();
                    json.put(unitFieldAttr.getAttr(),unit);
                    unitStr = ItemUtil.getCustomItemList(unitFieldAttr,json).toString();
                }
                MobileDetailScriptPojo stockPojo = new MobileDetailScriptPojo();
               /* //最多保留6位小数
                double d = stock;
                int a=(d+"").length()-(d+"").indexOf(".")-1;
                if (a > 6) {
                    String num = String.format("%.6f", d);
                    stockPojo.setNumScript(num + unitStr);
                } else {
                    stockPojo.setNumScript(stock + unitStr);
                }*/
                stockPojo.setNumScript(attrDecimalPrecisionHelper.formatPrecisionWithIntegerOnly(stock, explainMap.getOrDefault(ProductEnum.STOCK.getAttr(), new FieldAttrEntity())) + unitStr);
                scriptPojoList.add(stockPojo);
                break;
            case PURCHASE:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, PurchaseEnum.TOTAL_MONEY.getAttr(), scriptPojoList);
                break;
            case CONTRACT:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, ContractEnum.AMOUNT.getAttr(), scriptPojoList);
                break;
            case PAYMENT:
                FieldAttrEntity paymentAmountAttr = explainMap.getOrDefault(PaymentEnum.AMOUNT.getAttr(),new FieldAttrEntity());
                FieldAttrEntity realAmountAttr = explainMap.getOrDefault(PaymentEnum.REAL_AMOUNT.getAttr(),new FieldAttrEntity());
                Double amount = getDoubleOrDefaultFromFormData(data, PaymentEnum.AMOUNT.getAttr(), 0D);
                Integer isRed = getIntegerOrDefaultFromFormData(data, PaymentEnum.IS_RED.getAttr(), 0);
                String paymentAmountStr;
                if (Objects.equals(isRed, BasicConstant.ONE)) {
                    amount = getDoubleOrDefaultFromFormData(data, PaymentEnum.REAL_AMOUNT.getAttr(), 0D);
                    paymentAmountStr = amountParse(realAmountAttr,amount);
                }else {
                    paymentAmountStr = amountParse(paymentAmountAttr,amount);
                }
                MobileDetailScriptPojo paymentAmountPojo = new MobileDetailScriptPojo();
                paymentAmountPojo.setMoneyScript(paymentAmountStr + UnitEnum.MONEY.getName());
                scriptPojoList.add(paymentAmountPojo);
                break;
            case PAY_PLAN:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, PayPlanEnum.AMOUNT.getAttr(), scriptPojoList);
                break;
            case RETURNED_PURCHASE:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, ReturnedPurchaseEnum.TOTAL_MONEY.getAttr(), scriptPojoList);
                break;
            case REFUND:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, RefundEnum.RETURN_AMOUNT.getAttr(), scriptPojoList);
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                String instockStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, InstockEnum.TYPE.getAttr(), "");
                FieldAttrEntity instockStatusAttr = explainMap.get(InstockEnum.TYPE.getAttr());
                if (instockStatusAttr != null) {
                    List<ItemPoJo> items = instockStatusAttr.getItems();
                    for (ItemPoJo itemPoJo : items) {
                        if (Objects.equals(itemPoJo.getValue(), instockStatus)) {
                            MobileDetailScriptPojo instockTypePojo = new MobileDetailScriptPojo();
                            instockTypePojo.setStatusScript(itemPoJo.getText());
                            scriptPojoList.add(instockTypePojo);
                            break;
                        }
                    }
                }
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                String outstockStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, OutstockEnum.TYPE.getAttr(), "");
                FieldAttrEntity outstockStatusAttr = explainMap.get(OutstockEnum.TYPE.getAttr());
                if (outstockStatusAttr != null) {
                    List<ItemPoJo> items = outstockStatusAttr.getItems();
                    for (ItemPoJo itemPoJo : items) {
                        if (Objects.equals(itemPoJo.getValue(), outstockStatus)) {
                            MobileDetailScriptPojo outstockTypePojo = new MobileDetailScriptPojo();
                            outstockTypePojo.setStatusScript(itemPoJo.getText());
                            scriptPojoList.add(outstockTypePojo);
                            break;
                        }
                    }
                }
                break;
            case INVENTORY:
                String inventoryStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, InventoryEnum.STATUS.getAttr(), "");
                FieldAttrEntity inventoryStatusAttr = explainMap.get(InventoryEnum.STATUS.getAttr());
                if (inventoryStatusAttr != null) {
                    List<ItemPoJo> items = inventoryStatusAttr.getItems();
                    for (ItemPoJo itemPoJo : items) {
                        if (Objects.equals(itemPoJo.getValue(), inventoryStatus)) {
                            MobileDetailScriptPojo inOutstockStatusPojo = new MobileDetailScriptPojo();
                            inOutstockStatusPojo.setStatusScript(itemPoJo.getText());
                            scriptPojoList.add(inOutstockStatusPojo);
                            break;
                        }
                    }
                }
                break;
            case TRANSFER:
                String transferStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, TransferEnum.STATUS.getAttr(), "");
                FieldAttrEntity transferStatusAttr = explainMap.get(TransferEnum.STATUS.getAttr());
                if (transferStatusAttr != null) {
                    List<ItemPoJo> items = transferStatusAttr.getItems();
                    for (ItemPoJo itemPoJo : items) {
                        if (Objects.equals(itemPoJo.getValue(), transferStatus)) {
                            MobileDetailScriptPojo transferInOutstockStatusPojo = new MobileDetailScriptPojo();
                            transferInOutstockStatusPojo.setStatusScript(itemPoJo.getText());
                            scriptPojoList.add(transferInOutstockStatusPojo);
                            break;
                        }
                    }
                }
                break;
            case WORKORDER:
                // TODO: 删除workorder
//                Integer actualTime = saasUpdateHelp.getIntegerFromFormData(data, WorkOrderEnum.ACTUAL_TIME.getAttr());
//                MobileDetailScriptPojo actualTimePojo = new MobileDetailScriptPojo();
//                actualTimePojo.setTimeScript(actualTime);
//                scriptPojoList.add(actualTimePojo);
                break;
            case ASSEMBLE:
                String status = I18nMessageUtil.getMessage(I18nStringConstant.TO_BE_IN_OUT);
                if (Objects.equals(flowStatus, FlowStatusEnum.NOT_NEED_APPROVAL.getType()) || Objects.equals(flowStatus, FlowStatusEnum.PASS.getType())) {
                    status = I18nMessageUtil.getMessage(I18nStringConstant.IN_OUT);
                }
                MobileDetailScriptPojo assembleStatusPojo = new MobileDetailScriptPojo();
                assembleStatusPojo.setStatusScript(status);
                scriptPojoList.add(assembleStatusPojo);
                break;
            case COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                JSONArray communicateVideo = FastJsonHelper.getJsonArrFromFormData(data, CustomerCommunicateEnum.VIDEO.getAttr());
                if (communicateVideo != null && !communicateVideo.isEmpty()) {
                    MobileDetailScriptPojo communicateVideoPojo = new MobileDetailScriptPojo();
                    communicateVideoPojo.setVideoScript(true);
                    scriptPojoList.add(communicateVideoPojo);
                }

                JSONArray communicateFile = FastJsonHelper.getJsonArrFromFormData(data, CustomerCommunicateEnum.FILE.getAttr());
                if (communicateFile != null && !communicateFile.isEmpty()) {
                    MobileDetailScriptPojo communicateFilePojo = new MobileDetailScriptPojo();
                    communicateFilePojo.setFileScript(true);
                    scriptPojoList.add(communicateFilePojo);
                }
                break;
            case JXC_COMMUNICATE:
                JSONArray jxcCommunicateVideo = FastJsonHelper.getJsonArrFromFormData(data, SupplierCommunicateEnum.VIDEO.getAttr());
                if (jxcCommunicateVideo != null && !jxcCommunicateVideo.isEmpty()) {
                    MobileDetailScriptPojo jxcCommunicateVideoPojo = new MobileDetailScriptPojo();
                    jxcCommunicateVideoPojo.setVideoScript(true);
                    scriptPojoList.add(jxcCommunicateVideoPojo);
                }

                JSONArray jxcCommunicateFile = FastJsonHelper.getJsonArrFromFormData(data, SupplierCommunicateEnum.FILE.getAttr());
                if (jxcCommunicateFile != null && !jxcCommunicateFile.isEmpty()) {
                    MobileDetailScriptPojo jxcCommunicateFilePojo = new MobileDetailScriptPojo();
                    jxcCommunicateFilePojo.setFileScript(true);
                    scriptPojoList.add(jxcCommunicateFilePojo);
                }
                break;
            case INVOICE:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap,InvoiceEnum.TOTAL_MONEY.getAttr(), scriptPojoList);
                break;
            case PURCHASE_INVOICE:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(),scriptPojoList);
                break;
            case PAYMENT_SHEET:
                //预收款核销、红冲预收款核销(退到余额)类型回款单要读取核销金额字段，其他类型回款单读取回款金额字段
                Double sheetAmount;
                boolean writeOffPrepaymentFlag = SheetTypeEnum.onlyWriteOffAmount(sheetTypeEnum.getCode());
                FieldAttrEntity amountAttr;
                if (writeOffPrepaymentFlag) {
                    //预收款核销、红冲预收款核销(退到余额)，是用的核销金额
                    sheetAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr(), 0D);
                    amountAttr = explainMap.getOrDefault(PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr(),new FieldAttrEntity());
                } else {
                    sheetAmount = getDoubleOrDefaultFromFormData(data, PaymentSheetEnum.AMOUNT.getAttr(), 0D);
                    amountAttr = explainMap.getOrDefault(PaymentSheetEnum.AMOUNT.getAttr(),new FieldAttrEntity());
                }
                String sheetAmountStr = amountParse(amountAttr, sheetAmount);
                paymentAmountPojo = new MobileDetailScriptPojo();
                paymentAmountPojo.setMoneyScript(sheetAmountStr + UnitEnum.MONEY.getName());
                scriptPojoList.add(paymentAmountPojo);
                break;
            case PAY_SHEET:
                //预付款核销类型付款单要读取核销金额字段，其他类型付款单读取付款金额字段
                writeOffPrepaymentFlag = Objects.equals(sheetTypeEnum, SheetTypeEnum.WRITE_OFF_PREPAY);
                if (writeOffPrepaymentFlag) {
                    //预付款核销，是用的核销金额
                    sheetAmount = getDoubleOrDefaultFromFormData(data, PaySheetEnum.WRITE_OFF_AMOUNT.getAttr(), 0D);
                    amountAttr = explainMap.getOrDefault(PaySheetEnum.WRITE_OFF_AMOUNT.getAttr(),new FieldAttrEntity());
                } else {
                    sheetAmount = getDoubleOrDefaultFromFormData(data, PaySheetEnum.AMOUNT.getAttr(), 0D);
                    amountAttr = explainMap.getOrDefault(PaySheetEnum.AMOUNT.getAttr(),new FieldAttrEntity());
                }
                sheetAmountStr = amountParse(amountAttr, sheetAmount);
                paymentAmountPojo = new MobileDetailScriptPojo();
                paymentAmountPojo.setMoneyScript(sheetAmountStr + UnitEnum.MONEY.getName());
                scriptPojoList.add(paymentAmountPojo);
                break;
            case OTHER_INCOME:
                sheetAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, OtherIncomeEnum.AMOUNT.getAttr(), 0D);
                amountAttr = explainMap.getOrDefault(OtherIncomeEnum.AMOUNT.getAttr(),new FieldAttrEntity());
                sheetAmountStr = amountParse(amountAttr, sheetAmount);
                paymentAmountPojo = new MobileDetailScriptPojo();
                paymentAmountPojo.setMoneyScript(sheetAmountStr + UnitEnum.MONEY.getName());
                scriptPojoList.add(paymentAmountPojo);
                break;
            case OTHER_EXPENSE:
                sheetAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, OtherExpenseEnum.AMOUNT.getAttr(), 0D);
                amountAttr = explainMap.getOrDefault(OtherExpenseEnum.AMOUNT.getAttr(),new FieldAttrEntity());
                sheetAmountStr = amountParse(amountAttr, sheetAmount);
                paymentAmountPojo = new MobileDetailScriptPojo();
                paymentAmountPojo.setMoneyScript(sheetAmountStr + UnitEnum.MONEY.getName());
                scriptPojoList.add(paymentAmountPojo);
                break;
            case PAYMENT_TASK:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap,PaymentTaskEnum.PAYMENT_TASK_NUM.getAttr(), scriptPojoList);
                break;
            case ORDER:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, OrderEnum.AMOUNT.getAttr(), scriptPojoList);
                break;
            case DISTRIBUTOR_ACCOUNT:
                MobileDetailScriptPojo pojo = new MobileDetailScriptPojo();
                pojo.setStatusScript(DistributorAccountStatusEnum.getByCode(data.getString(DistributorAccountEnum.ACCOUNT_STATUS.getAttr())));
                scriptPojoList.add(pojo);
                break;
            case ORDER_OUTSTOCK:
                pojo = new MobileDetailScriptPojo();
                pojo.setStatusScript(OrderOutStockExpressStatusEnum.getNameByCode(data.getString(OrderOutStockEnum.EXPRESS_STATUS.getAttr())));
                scriptPojoList.add(pojo);
                break;
            case RETURN:
                setDetailShowScript(paasFormDataEntityExt, businessType, data, explainMap, ReturnEnum.RETURN_AMOUNT.getAttr(), scriptPojoList);
                break;
            default:
                break;
        }
        return scriptPojoList;
    }

    private String amountParse(FieldAttrEntity fieldAttrEntity,Double amount){
        String amountStr;
        if(AmountFlagEnum.YES.getType().equals(fieldAttrEntity.getAmountFlag())){
            Object contractAmountThousandth = AttrDecimalPrecisionHelper.parseThousandth(amount,fieldAttrEntity.getAccuracy());
            amountStr = String.valueOf(contractAmountThousandth);
        }else {
            amount = AttrDecimalPrecisionHelper.setDecimalPrecision(amount,fieldAttrEntity.getAccuracy());
            amountStr = String.valueOf(amount);
        }
        return amountStr;
    }

    /**
     * 获取移动端详情基础信息右上角的操作
     *
     * @param corpid       公司id
     * @param userId       用户id
     * @param businessType 业务类型
     * @param dataId       数据id
     * @param data         表单数据
     * @return List
     * @author GuoJun.HU
     * @date 2019/3/13 11:10
     * @since V1.0
     */
    private Map<String, Object> getDetailShowOperation(String corpid, String userId, Integer businessType, Long dataId, JSONObject data) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Integer isFocus = 0;
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        List<Long> pushNotifyList;
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                //关注
                boolean isCusShare;
                try {
                    isCusShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getAlias(), BasicConstant.IS_USE.toString());
                } catch (XbbException e) {
                    isCusShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getValue(), BasicConstant.IS_USE.toString());
                }
                Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", corpid);
                if(!isCusShare) {
                    map.put("userId", userId);
                }
                map.put("customerIdIn", Collections.singletonList(dataId));
                map.put("del", DelEnum.NORMAL.getDel());
                map.put("focus", BasicConstant.IS_USE);
                List<CustomerFocusEntity> customerFocusEntityList = customerFocusModel.findEntitys(map);
                isFocus = customerFocusEntityList != null && customerFocusEntityList.size() > 0 ? BasicConstant.IS_USE : BasicConstant.NO_USE;
                //有提醒的客户
                pushNotifyList = new ArrayList<>();
                saasListHelp.getPushNotify(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), pushNotifyList);
                if (!pushNotifyList.isEmpty()) {
                    param.put("message", true);
                }
                param.put("isFocus", isFocus);
                break;
            case SALES_OPPORTUNITY:
                // 关注
                boolean isOppShare;
                try {
                    isOppShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getAlias(), BasicConstant.IS_USE.toString());
                } catch (XbbException e) {
                    isOppShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getValue(), BasicConstant.IS_USE.toString());
                }
                map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", corpid);
                if(!isOppShare) {
                    map.put("userId", userId);
                }
                map.put("opportunityIdIn", Collections.singletonList(dataId));
                map.put("del", DelEnum.NORMAL.getDel());
                map.put("focus", BasicConstant.IS_USE);
                List<OpportunityFocusEntity> opportunityFocusEntityList = opportunityFocusModel.findEntitys(map);
                isFocus = opportunityFocusEntityList != null && opportunityFocusEntityList.size() > 0 ? BasicConstant.IS_USE : BasicConstant.NO_USE;
                param.put("isFocus", isFocus);
                //有提醒的机会
                pushNotifyList= new ArrayList<>();
                saasListHelp.getPushNotify(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), pushNotifyList);
                if (!pushNotifyList.isEmpty()) {
                    param.put("message", true);
                }
                break;
            case INVOICE:
                Integer invoiceHasRed = getIntegerOrDefaultFromFormData(data, InvoiceEnum.HAS_RED.getAttr(), 0);
                if (Objects.equals(invoiceHasRed, 1)) {
                    // 红冲发票
                    param.put("isRed", 1);
                }
                break;
            case PURCHASE_INVOICE:
                Integer purchaseInvoiceHasRed = getIntegerOrDefaultFromFormData(data,PurchaseInvoiceEnum.HAS_RED.getAttr(), 0);
                if (Objects.equals(purchaseInvoiceHasRed, 1)) {
                    // 红冲发票
                    param.put("isRed", 1);
                }
                break;
            case QUOTATION:
                //有提醒的报价单
                pushNotifyList = new ArrayList<>();
                saasListHelp.getPushNotify(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.QUOTATION.getCode(), pushNotifyList);
                if (!pushNotifyList.isEmpty()) {
                    param.put("message", true);
                }
                break;
            case CONTRACT:
                //有提醒的合同
                pushNotifyList = new ArrayList<>();
                saasListHelp.getPushNotify(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.CONTRACT.getCode(), pushNotifyList);
                if (!pushNotifyList.isEmpty()) {
                    param.put("message", true);
                }
                break;
            case CLUE:
                //有提醒的线索
                pushNotifyList = new ArrayList<>();
                saasListHelp.getPushNotify(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.CLUE.getCode(), pushNotifyList);
                if (!pushNotifyList.isEmpty()) {
                    param.put("message", true);
                }
                break;
            case ORDER:
                //有提醒的合同
                pushNotifyList = new ArrayList<>();
                saasListHelp.getPushNotify(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.ORDER.getCode(), pushNotifyList);
                if (!pushNotifyList.isEmpty()) {
                    param.put("message", true);
                }
                break;
            default:
                break;
        }
        return param;
    }

    /**
     * 通过摘要字段获取摘要内容
     *
     * @param summaryList 摘要内容
     * @param attr        字段
     * @return SummaryDataPoJo
     * @author GuoJun.HU
     * @date 2019/4/4 10:49
     * @since V1.0
     */
    private SummaryDataPoJo getSummaryDataPoJoByAttr(List<SummaryDataPoJo> summaryList, String attr) {
        return SummaryUtil.getSummaryDataPoJoByAttr(summaryList, attr);
    }

    /**
     * 获取移动端详情状态区块信息
     *
     * @param corpid         公司id
     * @param data           数据
     * @param dictionaryEnum 数据字典项
     * @param dictionaryAttr 数据字典项对应的attr
     * @return MobileDetailStatusBlockPojo
     * @author GuoJun.HU
     * @date 2019/4/9 16:14
     * @since V1.0
     */
    private MobileDetailStatusBlockPojo getMobileDetailStatusBlockPojo(String corpid, JSONObject data,
                                                                       DictionaryEnum dictionaryEnum, String dictionaryAttr, Integer editable) throws XbbException {
        List<ItemPoJo> itemPoJoList = dataDictionaryModel.getDictionaryList4Saas(dictionaryEnum, corpid, null);
        String currentCustomerStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, dictionaryAttr, "");
        itemPoJoList.forEach(itemPoJo -> {
            if (Objects.equals(itemPoJo.getValue(), currentCustomerStatus)) {
                itemPoJo.setChecked(true);
            }
        });
        MobileDetailStatusBlockPojo statusBlockPojo = new MobileDetailStatusBlockPojo();
        statusBlockPojo.setEditable(editable);
        statusBlockPojo.setOptions(itemPoJoList);
        return statusBlockPojo;
    }

    /**
     * 详情页数据穿透格式化数据
     *
     * @param list 数据
     * @param businessType 业务类型
     * @param corpid 公司
     * @throws
     * @author long.rao
     * @date 2019-05-08 10:26
     */
    private void formatData(List<PaasFormDataEntityExt> list, Integer businessType, String corpid, List<FieldAttrEntity> explainList) throws XbbException{
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        if (list.isEmpty() || list.size() < 1) {
            return;
        }
        Long formId = list.get(0).getFormId();
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                setMainUser(list, businessType, corpid);
                Map<String,String> industryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<ItemPoJo> industryList = dataDictionaryModel.getDictionaryList4Attr(CustomerManagementEnum.INDUSTRY.getSaasAttr(), corpid, formId);
                for (ItemPoJo itemPoJo : industryList){
                    industryMap.put(itemPoJo.getValue().toString(),itemPoJo.getText());
                }

                List<ItemPoJo> scaleList = dataDictionaryModel.getDictionaryList4Attr(CustomerManagementEnum.SCALE.getSaasAttr(), corpid, formId);
                Map<String,String> scaleMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ItemPoJo itemPoJo : scaleList){
                    scaleMap.put(itemPoJo.getValue().toString(),itemPoJo.getText());
                }

                List<ItemPoJo> isIndividualList = dataDictionaryModel.getDictionaryList4Attr(CustomerManagementEnum.IS_INDIVIDUAL.getSaasAttr(), corpid, formId);
                Map<String,String> isIndividualMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ItemPoJo itemPoJo : isIndividualList){
                    isIndividualMap.put(itemPoJo.getValue().toString(),itemPoJo.getText());
                }

                List<ItemPoJo> customerStatusList = dictionaryService.getArrayList(DictionaryEnum.CUSTOMER_STATUS, corpid, null);
                Map<String,String> typeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ItemPoJo itemPoJo : customerStatusList){
                    typeMap.put(itemPoJo.getValue().toString(),itemPoJo.getText());
                }
                for (PaasFormDataEntityExt customer : list) {
                    JSONObject data = customer.getData();
                    String type = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.TYPE.getAttr(), "");
                    String typeStr = typeMap.getOrDefault(type, "");
                    String scale = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.SCALE.getAttr(), "");
                    String scaleStr = scaleMap.getOrDefault(scale, "");
                    String isIndividual = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.IS_INDIVIDUAL.getAttr(), "");
                    String isIndividualStr = isIndividualMap.getOrDefault(isIndividual, "");
                    String industry = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.INDUSTRY.getAttr(), "");
                    String industryStr = industryMap.getOrDefault(industry, "");

                    data.put(CustomerManagementEnum.TYPE.getAttr(), typeStr);
                    data.put(CustomerManagementEnum.SCALE.getAttr(), scaleStr);
                    data.put(CustomerManagementEnum.IS_INDIVIDUAL.getAttr(), isIndividualStr);
                    data.put(CustomerManagementEnum.INDUSTRY.getAttr(), industryStr);
                    customer.setData(data);
                }
                break;
            case CONTRACT:
                setMainUser(list, businessType, corpid);
                formatSignPerson(list, corpid);
                break;
            case PAYMENT:
                List<ItemPoJo> statusItems = new ArrayList<>();
                explainList.forEach(item ->{
                    if (Objects.equals(item.getAttr(), PaymentEnum.STATUS.getAttr())) {
                        statusItems.addAll(item.getItems());
                    }
                });
                Map<Object, String> statusMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                statusItems.forEach(item ->{
                    statusMap.put(item.getValue(), item.getText());
                });
                for (PaasFormDataEntityExt payment : list) {
                    JSONObject data = payment.getData();
                    showFormatHelp.formatLinkBusiness4Show(data, PaymentEnum.CUSTOMER.getAttr(), PaymentEnum.CUSTOMER_LINK_TEXT.getAttr(), PaymentEnum.CUSTOMER.getFieldType());
                    showFormatHelp.formatLinkBusiness4Show(data, PaymentEnum.CONTRACT.getAttr(), PaymentEnum.CONTRACT_LINK_TEXT.getAttr(), PaymentEnum.CONTRACT.getFieldType());
                    String status = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentEnum.STATUS.getAttr(), "");
                    data.put(PaymentEnum.STATUS.getAttr(), statusMap.getOrDefault(status, ""));
                    payment.setData(data);
                }
                break;
            case SALES_OPPORTUNITY:
                setMainUser(list, businessType, corpid);
                Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", corpid);
                map.put("formId", formId);
                map.put("del", DelEnum.NORMAL.getDel());
                map.put("enable", 1);
                List<SaleStageEntity> salesStageList = saleStageModel.findEntitys(map);
                // 封装所有 销售状态 到 HashMap 中便于之后销售机会 无序查找销售阶段 type
                HashMap<String, String> salesCodeNameMap = new HashMap<>(salesStageList.size());
                for (SaleStageEntity salesStage : salesStageList) {
                    salesCodeNameMap.put(salesStage.getCode().toString(), salesStage.getName());
                }
                for (PaasFormDataEntityExt opp : list) {
                    JSONObject data = opp.getData();
                    showFormatHelp.formatLinkBusiness4Show(data, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), SalesOpportunityEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), SalesOpportunityEnum.CUSTOMER_NAME.getFieldType());
                    String stage = FastJsonHelper.getStringOrDefaultFromFormData(data, SalesOpportunityEnum.SALE_STAGE.getAttr(), "");
                    String stageStr = salesCodeNameMap.getOrDefault(stage, I18nMessageUtil.getMessage(I18nStringConstant.NOT_SET_UP));
                    data.put(SalesOpportunityEnum.SALE_STAGE.getAttr(), stageStr);
                }
                break;
            default:
                break;

        }

    }

    /**
     * 设置负责人
     *
     * @param list 数据
     * @param businessType 业务类型
     * @param corpid 公司
     * @author long.rao
     * @date 2019-05-08 10:24
     */
    private void setMainUser(List<PaasFormDataEntityExt> list, Integer businessType, String corpid){
        if (list == null || list.isEmpty()) {
            return;
        }
        List<Long> dataIdList = new ArrayList<>();
        for (PaasFormDataEntityExt entity : list) {
            dataIdList.add(entity.getDataId());
        }
        Map<Long,String> mainUserMap = userTeamService.getMainUserMap(dataIdList,corpid,businessType, false);
        for (PaasFormDataEntityExt entity : list){
            JSONObject data = entity.getData();
            data.put(FieldTypeEnum.OWNERID.getAlias(),mainUserMap.getOrDefault(entity.getDataId(),""));
            entity.setData(data);
        }
    }

    /**
     * 处理合同签订人
     *
     * @param list 数据
     * @param corpid 公司
     * @throws
     * @author long.rao
     * @date 2019-05-08 10:30
     */
    private void formatSignPerson(List<PaasFormDataEntityExt> list, String corpid) throws XbbException{
        List<String> signIds = new ArrayList<>();
        for (PaasFormDataEntityExt entity : list) {
            String signPerson = FastJsonHelper.getStringOrDefaultFromFormData(entity.getData(), ContractEnum.SIGN_PERSON.getAttr(), "");
            signIds.add(signPerson);
        }
        List<UserEntity> userEntities = userModel.getByUserIdIn(corpid, signIds, true);
        Map<String, String> userIdNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userEntities.forEach(item ->{
            userIdNameMap.put(item.getUserId(), item.getName());
        });
        for (PaasFormDataEntityExt entity : list){
            JSONObject data = entity.getData();
            String signPerson = FastJsonHelper.getStringOrDefaultFromFormData(entity.getData(), ContractEnum.SIGN_PERSON.getAttr(), "");
            showFormatHelp.formatLinkBusiness4Show(data, ContractEnum.LINK_CUSTOMER.getAttr(), ContractEnum.LINK_CUSTOMER_HIDE.getAttr(), ContractEnum.LINK_CUSTOMER.getFieldType());
            data.put(ContractEnum.SIGN_PERSON.getAttr(), userIdNameMap.getOrDefault(signPerson,""));
            entity.setData(data);
        }
    }

    /**
     * app端：格式化穿透后的业务
     *
     * @param mobileDetailThroughDTO
     * @param list 业务list
     * @param resultThroughVO 穿透返回vo
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author long.rao
     * @date 2019-05-29 14:43
     */
    private ResultThroughVO formatList(MobileDetailThroughDTO mobileDetailThroughDTO, List list, ResultThroughVO resultThroughVO) throws XbbException{
        Integer businessType = mobileDetailThroughDTO.getBusinessType();
        String corpid = mobileDetailThroughDTO.getCorpid();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        // resultThroughVO.setHead(redundantTemplateTypeEnum.getName());
        switch (redundantTemplateTypeEnum) {
            case COMMUNICATE:
                return formatCommunicate4App(mobileDetailThroughDTO, list, resultThroughVO);
            case SALES_OPPORTUNITY:
                return formatOpportunity4App(corpid, list, resultThroughVO);
            case CONTRACT:
                //内部判断是否为红冲合同，是则跳入退货退款展示
                return formatContract4App(mobileDetailThroughDTO,list, resultThroughVO);
            case PAYMENT:
                return formatPayment4App(corpid, list, resultThroughVO);
            case PURCHASE:
                return formatPurchase4App(corpid, list, resultThroughVO);
            case QUOTATION:
                return formatQuotation4App(corpid, list, resultThroughVO);
            default:
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
    }

    /**
     * app端：格式化穿透后的跟进记录业务
     * @param mobileDetailThroughDTO 移动端详情页穿透传参
     * @param list 业务list
     * @param resultThroughVo 穿透返回vo
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author long.rao
     * @date 2019-05-29 14:46
     */
    private ResultThroughVO formatCommunicate4App(MobileDetailThroughDTO mobileDetailThroughDTO, List<PaasFormDataEntityExt> list, ResultThroughVO resultThroughVo) throws XbbException {
        resultThroughVo.setBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());
        String corpid = mobileDetailThroughDTO.getCorpid();
        String userId = mobileDetailThroughDTO.getUserId();
        //创建人ids、客户ids
        List<Long> dataIdIn = new ArrayList<>();
        Set<String> userIdIn = new HashSet<>();
        Set<Long> customerIdIn = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : list) {
            dataIdIn.add(entityExt.getDataId());
            userIdIn.add(entityExt.getCreatorId());
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            customerIdIn.add(data.getLongValue(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr()));
        }
        dataIdIn.add(-1L);
        Map<Long, Integer> commnetCountMap = paasCommentModel.getCommnetCountMap(dataIdIn, corpid, BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
        Map<Long, Integer> likeCountMap = likeModel.getLikeCountMap(dataIdIn, corpid, BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
        List<Long> hasCommentIdList = paasCommentModel.hasMyComment(dataIdIn, corpid, BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode(), userId);
        List<Long> hasLikeIdList = likeModel.hasMyLike(dataIdIn, corpid, BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode(), userId);
        //员工id--员工实体
        Map<String, UserEntity> userMap = commonHelp.getUserMapByIds(corpid, userIdIn);
        //客户id-名称map
        CustomerManagementEnum customerNameEnum = CustomerManagementEnum.NAME;
        List<String> fieldList = Arrays.asList("id", "dataId", CustomerManagementEnum.getAttrConnectData(customerNameEnum));
        IndexTypeEnum indexTypeEnum =  indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        Map<Long, String> customerIdNameMap = formHelp.getFormIdAttrMapByIds4All(customerNameEnum.getAttr(), corpid, indexTypeEnum, customerIdIn, fieldList);
        //查询出跟进记录的表单id
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), corpid);
        //TODO
        //获取启用的跟进方式
        Map<String, String> typeMap = dataDictionaryModel.getDictionaryMap4Saas(DictionaryEnum.COMMUNICATE_TYPE, corpid, paasFormEntityExt.getId());
        //最终结果
        List<CustomerCommunicatePojo> customerCommunicatePojoList = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : list) {
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long customerId = data.getLong(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
            String customerName = customerIdNameMap.getOrDefault(customerId, "");
            String creatorId = entityExt.getCreatorId();
            UserEntity creatUser = userMap.getOrDefault(creatorId, new UserEntity());
            String userName = creatUser.getName();
            String userAvatar = creatUser.getAvatar();
            userAvatar = userAvatar == null ? "" : userAvatar;

            CustomerCommunicatePojo customerCommunicatePojo = commonHelp.setCustomerCommunicatePojo(commnetCountMap, likeCountMap, hasCommentIdList, hasLikeIdList, entityExt, data, customerId, customerName, typeMap, creatorId, userName, Collections.singletonList(userAvatar));
            customerCommunicatePojoList.add(customerCommunicatePojo);
        }
        CommunicateVO communicateVo = new CommunicateVO();
        communicateVo.setResultMap(customerCommunicatePojoList);
        communicateVo.setPageHelper(resultThroughVo.getPageHelper());
        resultThroughVo.setDataApp(communicateVo);
        return resultThroughVo;
    }

    /**
     * app端：格式化穿透后的机会业务
     * @param corpid 公司id
     * @param list 业务list
     * @param resultThroughVo 穿透返回vo
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author zcp
     * @date 2019/5/12 20:16
     * @since v1.0
     * @version v1.0
     */
    private ResultThroughVO formatOpportunity4App(String corpid, List<PaasFormDataEntityExt> list, ResultThroughVO resultThroughVo) throws XbbException {
        resultThroughVo.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        //机会ids、创建人ids、客户ids
        Set<Long> opportunityIdIn = new HashSet<>();
        Set<String> userIdIn = new HashSet<>();
        Set<Long> customerIdIn = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : list) {
            opportunityIdIn.add(entityExt.getId());
            userIdIn.add(entityExt.getCreatorId());
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            customerIdIn.add(data.getLongValue(SalesOpportunityEnum.CUSTOMER_NAME.getAttr()));
        }
        //有提醒的机会
        List<Long> pushNotifyList = new ArrayList<>();
        pushModel.getPushNotify(opportunityIdIn, corpid, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), pushNotifyList);
        //员工id--员工名称
        Map<String, String> userNameMap = commonHelp.getUserNameMapByIds(corpid, userIdIn);
        List<PaasFormDataEntity> teamUserList = formHelp.getUserTeamListByIds(IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM, corpid, opportunityIdIn, BasicConstant.MAIN_USER, PaasFormDataEntity.class);
        List<OpportunityUserEntity> userTeamEntities = (List<OpportunityUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM, teamUserList);

        //customerId--负责人名称
        Map<Long, String> ownerNameMap = commonHelp.getUserTeamNameMap(userTeamEntities);
        //客户id-名称map
        CustomerManagementEnum customerNameEnum = CustomerManagementEnum.NAME;
        List<String> fieldList = Arrays.asList("id", "dataId", CustomerManagementEnum.getAttrConnectData(customerNameEnum));
        IndexTypeEnum indexTypeEnum =  indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        Map<Long, String> customerIdNameMap = formHelp.getFormIdAttrMapByIds4All(customerNameEnum.getAttr(), corpid, indexTypeEnum, customerIdIn, fieldList);
        Map<String, String> allStageMap = saleStageModel.getAllStageMap(corpid);
        //最终结果
        List<AppListPojo> appListPojos = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : list) {
            List<SummaryDataPoJo> summaryList = new ArrayList<>();
            List<FormTitlePoJo> titleList = new ArrayList<>();

            Long id = entityExt.getId();
            long appId = entityExt.getAppId();
            long menuId = entityExt.getMenuId();
            long formId = entityExt.getFormId();
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long customerId = data.getLong(SalesOpportunityEnum.CUSTOMER_NAME.getAttr());
            String name = (String) data.getOrDefault(SalesOpportunityEnum.NAME.getAttr(), "");
            String no = entityExt.getSerialNo();
            String customerName = customerIdNameMap.getOrDefault(customerId, "");
            String staleStage =  allStageMap.getOrDefault(entityExt.getFormId() + StringConstant.CROSS + data.getString(SalesOpportunityEnum.SALE_STAGE.getAttr()), "");
            String timeStr = "";
            Long time = data.getLong(SalesOpportunityEnum.ESTIMATE_END_TIME.getAttr());
            if (time != null && time > 0) {
                timeStr = DateTimeUtil.getStringEpochSecond(time, DateTimeUtil.SDFDate);
            }
            String creator = userNameMap.getOrDefault(entityExt.getCreatorId(), "");
            String owner = ownerNameMap.getOrDefault(id, "");

            JSONArray explains = new JSONArray();
            JSONObject superScript = new JSONObject();
            JSONArray tags = new JSONArray();
            JSONObject others = new JSONObject();
            // 解释
            if(!StringUtil.isEmpty(owner)){
                //explains.add("负责人：" + owner);
                summaryList.add(commonHelp.setSummary(SalesOpportunityEnum.OWNER_ID.getAttrName(), owner));
            }
            if(!StringUtil.isEmpty(creator)){
                //explains.add("创建人：" + creator);
                summaryList.add(commonHelp.setSummary(SalesOpportunityEnum.CREATOR_ID.getAttrName(), creator));
            }
            //explains.add("关联客户：" + customerName);
            summaryList.add(commonHelp.setSummary(SalesOpportunityEnum.CUSTOMER_NAME.getAttrName(), customerName));
            String estimateEndTimeStr = SalesOpportunityEnum.ESTIMATE_END_TIME.getAttrName() + "：";
            //explains.add(estimateEndTimeStr + timeStr);
            summaryList.add(commonHelp.setSummary(SalesOpportunityEnum.ESTIMATE_END_TIME.getAttrName(), timeStr));
            // 角标
            superScript.put("message", pushNotifyList.contains(id) ? 1 : 0);
            /*-- 其他 -*/
            //格式化钱币
            String amountFormat = StringUtil.formatDouble(data.getDoubleValue(SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttr()));
            others.put("amount", amountFormat);
            others.put("salesStage", staleStage);

            titleList.add(commonHelp.setTitle(entityExt.getSerialNo()));

            appListPojos.add(new AppListPojo(id, titleList, summaryList, superScript, new ArrayList<>(), others, appId, menuId, formId));
        }
        ListAppVO listAppVo = new ListAppVO(appListPojos, resultThroughVo.getPageHelper().getRowsCount());
        resultThroughVo.setDataApp(listAppVo);
        return resultThroughVo;
    }

    /**
     * app端：格式化穿透后的合同业务
     * @param mobileDetailThroughDTO
     * @param list 业务list
     * @param resultThroughVo 穿透返回vo
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author long.rao
     * @date 2019-05-29 14:47
     */
    private ResultThroughVO formatContract4App(MobileDetailThroughDTO mobileDetailThroughDTO, List<PaasFormDataEntityExt> list, ResultThroughVO resultThroughVo) throws XbbException {
        String corpid = mobileDetailThroughDTO.getCorpid();
        resultThroughVo.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
        //签订人ids、合同ids、客户id
        Set<String> userIdIn = new HashSet<>();
        List<Long> contractIdIn = new ArrayList<>();
        Set<Long> customerIdIn = new HashSet<>();
        Set<Long> formIds = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : list) {
            contractIdIn.add(entityExt.getId());
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            userIdIn.add(data.getString(ContractEnum.SIGN_PERSON.getAttr()));
            customerIdIn.add(data.getLongValue(ContractEnum.LINK_CUSTOMER.getAttr()));
            formIds.add(entityExt.getFormId());
        }

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL);
        param.put("formIdIn", formIds);
        List<PaasFormExplainEntity> entityExt1 = paasFormExplainModel.findEntitys(param);
        Map<Long, Map<String, FieldAttrEntity>> fieldMap = new HashMap<>(entityExt1.size());
        entityExt1.forEach(item -> {
            List<FieldAttrEntity> fieldAttrEntities = JSONArray.parseArray(item.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> attrEntityMap = new HashMap<>(fieldAttrEntities.size());
            for (FieldAttrEntity entity : fieldAttrEntities) {
                attrEntityMap.put(entity.getAttr(), entity);
            }
            fieldMap.put(item.getFormId(), attrEntityMap);
        });


        //客户id-名称map
        CustomerManagementEnum customerNameEnum = CustomerManagementEnum.NAME;
        List<String> fieldList = Arrays.asList("id", "dataId", CustomerManagementEnum.getAttrConnectData(customerNameEnum));
        IndexTypeEnum indexTypeEnum =  indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        Map<Long, String> customerIdNameMap = formHelp.getFormIdAttrMapByIds4All(customerNameEnum.getAttr(), corpid, indexTypeEnum, customerIdIn, fieldList);
        //员工id--员工名称
        Map<String, String> userNameMap = commonHelp.getUserNameMapByIds(corpid, userIdIn);
        //获取启用的合同状态 合同和订单的合同状态不一致
        Map<String, String> contractStatusMap;
        if (Objects.equals(mobileDetailThroughDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
            contractStatusMap = new HashMap<>();
            List<ItemPoJo> itemPoJos = fieldMap.get(list.get(0).getFormId()).get(OrderEnum.STATUS.getAttr()).getItems();
            itemPoJos.forEach(item -> contractStatusMap.put(item.getValue().toString(), item.getText()));
        } else {
            contractStatusMap = dataDictionaryModel.getDictionaryMap(DictionaryEnum.CONTRACT_STATUS, corpid, null);
        }

        //有提醒的合同
        List<Long> pushNotifyList = new ArrayList<>();
        pushModel.getPushNotify(contractIdIn, corpid, XbbRefTypeEnum.CONTRACT.getCode(), pushNotifyList);

        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserIdMap(contractIdIn, corpid, XbbRefTypeEnum.CONTRACT.getCode(), false, mainUserMap, coUserMap);
        //最终结果
        List<AppListPojo> appListPojos = new ArrayList<>();
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(mobileDetailThroughDTO, handlerExplainDTO);
        Boolean amountHide;
        Boolean statusHide;
        Boolean linkCustomerHide;
        Boolean signTimeHide;
        Boolean signPersonHide;
        Boolean nameHide;
        Boolean noHide;
        for (PaasFormDataEntityExt entityExt : list) {
            List<SummaryDataPoJo> summaryList = new ArrayList<>();
            List<SummaryDataPoJo> lablesList = new ArrayList<>();
            List<FormTitlePoJo> titleList = new ArrayList<>();

            Long appId = entityExt.getAppId();
            Long menuId = entityExt.getMenuId();
            Long formId = entityExt.getFormId();
            Long contractId = entityExt.getId();

            handlerExplainDTO.setCreatorId(entityExt.getCreatorId());
            handlerExplainDTO.setOwnerId(mainUserMap.getOrDefault(contractId, new ArrayList<>()));
            handlerExplainDTO.setCoUserId(coUserMap.getOrDefault(contractId, new ArrayList<>()));

            Map<String, FieldAttrEntity> fieldAttrEntityMap = fieldMap.getOrDefault(formId, new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
            amountHide = ExplainUtil.isFieldNeedHide(fieldAttrEntityMap.getOrDefault(ContractEnum.AMOUNT.getAttr(), new FieldAttrEntity()), handlerExplainDTO);
            statusHide = ExplainUtil.isFieldNeedHide(fieldAttrEntityMap.getOrDefault(ContractEnum.STATUS.getAttr(), new FieldAttrEntity()), handlerExplainDTO);
            linkCustomerHide = ExplainUtil.isFieldNeedHide(fieldAttrEntityMap.getOrDefault(ContractEnum.LINK_CUSTOMER.getAttr(), new FieldAttrEntity()), handlerExplainDTO);
            signTimeHide = ExplainUtil.isFieldNeedHide(fieldAttrEntityMap.getOrDefault(ContractEnum.SIGN_TIME.getAttr(), new FieldAttrEntity()), handlerExplainDTO);
            signPersonHide = ExplainUtil.isFieldNeedHide(fieldAttrEntityMap.getOrDefault(ContractEnum.SIGN_PERSON.getAttr(), new FieldAttrEntity()), handlerExplainDTO);
            nameHide = ExplainUtil.isFieldNeedHide(fieldAttrEntityMap.getOrDefault(ContractEnum.NAME.getAttr(), new FieldAttrEntity()), handlerExplainDTO);
            noHide = ExplainUtil.isFieldNeedHide(fieldAttrEntityMap.getOrDefault(ContractEnum.CONTRACT_NO.getAttr(), new FieldAttrEntity()), handlerExplainDTO);

            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long customerId = data.getLong(ContractEnum.LINK_CUSTOMER.getAttr());
            Integer isRed = (Integer) data.getOrDefault(ContractEnum.IS_RED.getAttr(), 0);
            String signTime = DateTimeUtil.getStringEpochSecond(data.getLong(ContractEnum.SIGN_TIME.getAttr()), DateTimeUtil.SDFDate);
            String name = (String) data.getOrDefault(ContractEnum.NAME.getAttr(), "");
            String no = entityExt.getSerialNo();
            String status = contractStatusMap.getOrDefault(data.getString(ContractEnum.STATUS.getAttr()), "");
            String customerName = customerIdNameMap.getOrDefault(customerId, "");
            String amount = StringUtil.formatDouble(data.getDoubleValue(ContractEnum.AMOUNT.getAttr()));
            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();
            /*-- 解释 -*/
            if (nameHide) {
                name = "";
            }
            if (linkCustomerHide) {
                customerName = "";
            }
            //签订人or归属人
            String belongNameStr = userNameMap.getOrDefault(data.getString(OrderEnum.SIGN_PERSON.getAttr()), "");
            if (signPersonHide) {
                belongNameStr = "";
            }
            if (signTimeHide) {
                signTime = "";
            }
            if (Objects.equals(mobileDetailThroughDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                summaryList.add(commonHelp.setSummary(OrderEnum.LINK_DISTRIBUTOR.getAttrName(), customerName));
                summaryList.add(commonHelp.setSummary(OrderEnum.SIGN_PERSON.getAttrName(), belongNameStr));
                summaryList.add(commonHelp.setSummary(OrderEnum.SIGN_TIME.getAttrName(), signTime));
            } else {
                summaryList.add(commonHelp.setSummary(ContractEnum.NAME.getAttrName(), name));
                summaryList.add(commonHelp.setSummary(ContractEnum.LINK_CUSTOMER.getAttrName(), customerName));
                summaryList.add(commonHelp.setSummary(ContractEnum.SIGN_PERSON.getAttrName(), belongNameStr));
                summaryList.add(commonHelp.setSummary(ContractEnum.SIGN_TIME.getAttrName(), signTime));
            }
            /*-- 角标 -*/
            superScript.put("message", pushNotifyList.contains(contractId) ? 1 : 0);
            /*-- 标签 -*/
            if (statusHide) {
                status = "";
            }
            lablesList.add(commonHelp.setLable(ContractEnum.STATUS.getAttrName(), status));

            /*-- 其他 -*/
            if (amountHide) {
                amount = "";
            }
            others.put("amount", amount);
            others.put("isRed", isRed);
            if (noHide) {
                no = "";
            }
            titleList.add(commonHelp.setTitle(no));
            appListPojos.add(new AppListPojo(contractId, titleList, summaryList, superScript, lablesList, others, appId, menuId, formId));
        }
        ListAppVO listAppVo = new ListAppVO(appListPojos, resultThroughVo.getPageHelper().getRowsCount());
        resultThroughVo.setDataApp(listAppVo);
        return resultThroughVo;
    }

    /**
     * app端：格式化穿透后的应收款（已收款、未收款最终都展示应收款）
     * @param corpid 公司id
     * @param list 业务list
     * @param resultThroughVo 穿透返回vo
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author long.rao
     * @date 2019-05-29 14:47
     */
    private ResultThroughVO formatPayment4App(String corpid, List<PaasFormDataEntityExt> list, ResultThroughVO resultThroughVo) throws XbbException {
        resultThroughVo.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
        //应收款id、合同ids、客户id
        Set<Long> paymentIdIn = new HashSet<>();
        Set<Long> contractIdIn = new HashSet<>();
        Set<Long> customerIdIn = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : list) {
            paymentIdIn.add(entityExt.getId());
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            contractIdIn.add(data.getLongValue(PaymentEnum.CONTRACT.getAttr()));
            customerIdIn.add(data.getLongValue(PaymentEnum.CUSTOMER.getAttr()));
        }
        List<PaasFormDataEntity> paymentTeamList = formHelp.getUserTeamListByIds(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, corpid, paymentIdIn, BasicConstant.MAIN_USER, PaasFormDataEntity.class);
        List<PaymentUserEntity> teamUserList = (List<PaymentUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, paymentTeamList);
        //payemntId--负责人名称
        Map<Long, String> ownerNameMap = commonHelp.getUserTeamNameMap(teamUserList);
        //合同id-名称map
        ContractEnum contractNameEnum = ContractEnum.NAME;
        List<String> fieldList = Arrays.asList("id", "dataId", ContractEnum.getAttrConnectData(contractNameEnum));
        Map<Long, String> contractIdNameMap = formHelp.getFormIdAttrMapByIds4All(contractNameEnum.getAttr(), corpid, IndexTypeEnum.IDX_SAAS_CONTRACT, contractIdIn, fieldList);
        //客户id-名称map
        CustomerManagementEnum customerNameEnum = CustomerManagementEnum.NAME;
        fieldList = Arrays.asList("id", "dataId", CustomerManagementEnum.getAttrConnectData(customerNameEnum));
        IndexTypeEnum indexTypeEnum =  indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        Map<Long, String> customerIdNameMap = formHelp.getFormIdAttrMapByIds4All(customerNameEnum.getAttr(), corpid, indexTypeEnum, customerIdIn, fieldList);
        //最终结果
        Long now = DateTimeUtil.getInt();
        List<AppListPojo> appListPojos = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : list) {
            List<SummaryDataPoJo> summaryList = new ArrayList<>();
            List<FormTitlePoJo> titleList = new ArrayList<>();

            Long paymentId = entityExt.getId();
            Long appId = entityExt.getAppId();
            Long menuId = entityExt.getMenuId();
            Long formId = entityExt.getFormId();
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long contractId = data.getLong(PaymentEnum.CONTRACT.getAttr());
            Long customerId = data.getLong(PaymentEnum.CUSTOMER.getAttr());
            String owner = ownerNameMap.getOrDefault(paymentId, "");
            String contractName = contractIdNameMap.getOrDefault(contractId, "");
            String customerName = customerIdNameMap.getOrDefault(customerId, "");
            String statusStr = data.getString(PaymentEnum.STATUS.getAttr());
            String status = PaymentStatusEnum.getByCode(statusStr).getAlias();
            String timeStr = "";
            Long time = data.getLong(PaymentEnum.ESTIMATE_TIME.getAttr());
            if (time != null && time > 0) {
                timeStr = DateTimeUtil.getStringEpochSecond(time, DateTimeUtil.SDFDate);
            }
            JSONArray explains = new JSONArray();
            JSONObject superScript = new JSONObject();
            JSONArray tags = new JSONArray();
            JSONObject others = new JSONObject();
            /*-- 解释 -*/
            /*explains.add("关联合同：" + contractName);
            explains.add("客户名称：" + customerName);
            explains.add("负责人：" + owner);
            explains.add("预计回款日期：" + timeStr);*/
            summaryList.add(commonHelp.setSummary(PaymentEnum.CONTRACT.getAttrName(), contractName));
            summaryList.add(commonHelp.setSummary(PaymentEnum.CUSTOMER.getAttrName(), customerName));
            summaryList.add(commonHelp.setSummary(PaymentEnum.OWNER_ID.getAttrName(), owner));
            summaryList.add(commonHelp.setSummary(PaymentEnum.ESTIMATE_TIME.getAttrName(), timeStr));
            /*-- 其他 -*/
            Double amount =data.getDoubleValue(PaymentEnum.AMOUNT.getAttr());
            Double realAmount = data.getDoubleValue(PaymentEnum.REAL_AMOUNT.getAttr());
            if (realAmount < 0) {
                amount = realAmount;
            }
            String amountStr = StringUtil.formatDouble(amount);
            Integer isRed = (Integer) data.getOrDefault(PaymentEnum.IS_RED.getAttr(), 0);
            Integer isBad = 0;
            if ( Objects.equals(PaymentStatusEnum.getByAlias(status),PaymentStatusEnum.BAD_DEBT) ){
                isBad = 1;
            }
            commonHelp.setPaymentOthers(others, amountStr, status, isRed, isBad);

            titleList.add(commonHelp.setTitle(entityExt.getSerialNo()));
            appListPojos.add(new AppListPojo(paymentId, titleList, summaryList, superScript, new ArrayList<>(), others, appId, menuId, formId));
        }
        ListAppVO listAppVo = new ListAppVO(appListPojos, resultThroughVo.getPageHelper().getRowsCount());
        resultThroughVo.setDataApp(listAppVo);
        return resultThroughVo;
    }

    /**
     * app端：格式化穿透后的采购合同业务
     * @param corpid 公司id
     * @param list 业务list
     * @param resultThroughVo 穿透返回vo
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author zcp
     * @date 2019/5/16 21:47
     * @since v1.0
     * @version v1.0
     */
    private ResultThroughVO formatPurchase4App(String corpid, List<PaasFormDataEntityExt> list, ResultThroughVO resultThroughVo) throws XbbException {
        resultThroughVo.setBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
        //签订人ids、采购合同ids、供应商id
        Set<String> userIdIn = new HashSet<>();
        Set<Long> supplierIdIn = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : list) {
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            userIdIn.add(data.getString(PurchaseEnum.SIGNER_ID.getAttr()));
            supplierIdIn.add(data.getLongValue(PurchaseEnum.SUPPLIER_ID.getAttr()));
        }
        //员工id--员工名称
        Map<String, String> userNameMap = commonHelp.getUserNameMapByIds(corpid, userIdIn);
        //供应商id-名称map
        SupplierEnum supplierNameEnum = SupplierEnum.SUPPLIER_NAME;
        List<String> fieldList = Arrays.asList("id", "dataId", SupplierEnum.getAttrConnectData(supplierNameEnum));
        Map<Long, String> supplierIdNameMap = formHelp.getFormIdAttrMapByIds4All(supplierNameEnum.getAttr(), corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER, supplierIdIn, fieldList);
        //查询出采购合同的表单id
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PURCHASE.getCode(), corpid);
        Long formId = paasFormEntityExt == null ? null : paasFormEntityExt.getId();
        //获取启用的采购合同状态
        Map<String, String> purchaseStatusMap = dataDictionaryModel.getDictionaryMap4Saas(DictionaryEnum.PURCHASE_STATUS, corpid, formId);
        //最终结果
        List<AppListPojo> appListPojos = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : list) {
            List<SummaryDataPoJo> summaryList = new ArrayList<>();
            List<SummaryDataPoJo> lablesList = new ArrayList<>();
            List<FormTitlePoJo> titleList = new ArrayList<>();

            Long purchaseId = entityExt.getId();
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long supplierId = data.getLong(PurchaseEnum.SUPPLIER_ID.getAttr());
            String status = purchaseStatusMap.getOrDefault(data.getString(PurchaseEnum.STATUS.getAttr()), "");
            String supplierName = supplierIdNameMap.getOrDefault(supplierId, "");
            Long signTime = data.getLongValue(PurchaseEnum.SIGN_TIME.getAttr());
            String signTimeStr = DateTimeUtil.getStringEpochSecond(signTime, DateTimeUtil.SDFDate);
            String name = data.getString(PurchaseEnum.PURCHASE_NAME.getAttr());
            //签订人
            String belongNameStr = userNameMap.getOrDefault(data.getString(PurchaseEnum.SIGNER_ID.getAttr()), "");
            JSONArray explains = new JSONArray();
            JSONObject others = new JSONObject();
            JSONArray tags = new JSONArray();

            /*explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, PurchaseEnum.SUPPLIER_ID.getAttrName(), supplierName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, PurchaseEnum.SIGNER_ID.getAttrName(), belongNameStr));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, PurchaseEnum.SIGN_TIME.getAttrName(), signTimeStr));*/
            summaryList.add(commonHelp.setSummary(PurchaseEnum.PURCHASE_NAME.getAttrName(), name));
            summaryList.add(commonHelp.setSummary(PurchaseEnum.SUPPLIER_ID.getAttrName(), supplierName));
            summaryList.add(commonHelp.setSummary(PurchaseEnum.SIGNER_ID.getAttrName(), belongNameStr));
            summaryList.add(commonHelp.setSummary(PurchaseEnum.SIGN_TIME.getAttrName(), signTimeStr));

            String amount = StringUtil.formatDouble(data.getDoubleValue(PurchaseEnum.TOTAL_MONEY.getAttr()));
            String unit = I18nMessageUtil.getMessage(CommonConstant.YUAN);
            others.put(PurchaseEnum.TOTAL_MONEY.getSaasAttr(), amount + unit);
            if (!StringUtil.isEmpty(status)) {
                //tags.add(status);
                lablesList.add(commonHelp.setLable(PurchaseEnum.STATUS.getAttrName(), status));
            }

            titleList.add(commonHelp.setTitle(entityExt.getSerialNo()));
            appListPojos.add(new AppListPojo(purchaseId, titleList, summaryList, null, lablesList, others));
        }
        ListAppVO listAppVo = new ListAppVO(appListPojos, resultThroughVo.getPageHelper().getRowsCount());
        resultThroughVo.setDataApp(listAppVo);
        return resultThroughVo;
    }

    /**
     * Description: app端：格式化穿透后的报价单业务
     * @param corpid 公司id
     * @param list 业务list
     * @param resultThroughVo 穿透返回vo
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author 刘阳
     * @date 2019/9/4 11:07 AM
     * @since v1.0
     */
    private ResultThroughVO formatQuotation4App(String corpid, List<PaasFormDataEntityExt> list, ResultThroughVO resultThroughVo) throws XbbException {
        resultThroughVo.setBusinessType(XbbRefTypeEnum.QUOTATION.getCode());
        //签订人ids、合同ids、客户id
        Set<String> userIdIn = new HashSet<>();
        Set<Long> quotationIdIn = new HashSet<>();
        Set<Long> customerIdIn = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : list) {
            quotationIdIn.add(entityExt.getId());
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            userIdIn.add(data.getString(QuotationEnum.QUOTATION_PERSON.getAttr()));
            customerIdIn.add(data.getLongValue(QuotationEnum.CUSTOMER_ID.getAttr()));
        }
        //客户id-名称map
        CustomerManagementEnum customerNameEnum = CustomerManagementEnum.NAME;
        List<String> fieldList = Arrays.asList("id", "dataId", CustomerManagementEnum.getAttrConnectData(customerNameEnum));
        IndexTypeEnum indexTypeEnum =  indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        Map<Long, String> customerIdNameMap = formHelp.getFormIdAttrMapByIds4All(customerNameEnum.getAttr(), corpid, indexTypeEnum, customerIdIn, fieldList);
        //员工id--员工名称
        Map<String, String> userNameMap = commonHelp.getUserNameMapByIds(corpid, userIdIn);
        //获取启用的报价单状态
        /*Map<String, String> quotationStatusMap = dataDictionaryModel.getDictionaryMap(DictionaryEnum.QUOTATION_STATUS, corpid, null);*/
        //有提醒的报价单
        List<Long> pushNotifyList = new ArrayList<>();
        pushModel.getPushNotify(quotationIdIn, corpid, XbbRefTypeEnum.QUOTATION.getCode(), pushNotifyList);

        //最终结果
        List<AppListPojo> appListPojos = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : list) {
            List<SummaryDataPoJo> summaryList = new ArrayList<>();
            List<SummaryDataPoJo> lablesList = new ArrayList<>();
            List<FormTitlePoJo> titleList = new ArrayList<>();

            Long appId = entityExt.getAppId();
            Long menuId = entityExt.getMenuId();
            Long formId = entityExt.getFormId();
            Long contractId = entityExt.getId();
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long customerId = data.getLong(QuotationEnum.CUSTOMER_ID.getAttr());
            String quotationTime = DateTimeUtil.getStringEpochSecond(data.getLong(QuotationEnum.QUOTATION_TIME.getAttr()), DateTimeUtil.SDFDate);
            String name = (String) data.getOrDefault(QuotationEnum.NAME.getAttr(), "");
            String no = entityExt.getSerialNo();
            //String status = quotationStatusMap.getOrDefault(data.getString(QuotationEnum.STATUS.getAttr()), "");
            String customerName = customerIdNameMap.getOrDefault(customerId, "");
            String amount = StringUtil.formatDouble(data.getDoubleValue(QuotationEnum.AMOUNT.getAttr()));
            JSONArray explains = new JSONArray();
            JSONObject superScript = new JSONObject();
            JSONArray tags = new JSONArray();
            JSONObject others = new JSONObject();
            /*-- 解释 -*/
            /*explains.add("报价单名称：" + name);
            explains.add("关联客户：" + customerName);*/
            summaryList.add(commonHelp.setSummary(QuotationEnum.NAME.getAttrName(), name));
            summaryList.add(commonHelp.setSummary(QuotationEnum.CUSTOMER_ID.getAttrName(), customerName));
            //报价人
            String belongNameStr = userNameMap.getOrDefault(data.getString(QuotationEnum.QUOTATION_PERSON.getAttr()), "");
            /*explains.add("报价人:" + belongNameStr);
            explains.add("报价日期:" + signTime);*/
            summaryList.add(commonHelp.setSummary(QuotationEnum.QUOTATION_PERSON.getAttrName(), belongNameStr));
            summaryList.add(commonHelp.setSummary(QuotationEnum.QUOTATION_TIME.getAttrName(), quotationTime));
            /*-- 角标 -*/
            superScript.put("message", pushNotifyList.contains(contractId) ? 1 : 0);
            /*-- 标签 -*/
            //JsonHelperUtil.addToJSONArray(tags, contractStatusMap.getOrDefault(status, ""));
            //lablesList.add(commonHelp.setLable(ContractEnum.STATUS.getAttrName(), quotationStatusMap.getOrDefault(status, "") ));

            /*-- 其他 -*/
            others.put("amount", amount);

            titleList.add(commonHelp.setTitle(no));
            appListPojos.add(new AppListPojo(contractId, titleList, summaryList, superScript, lablesList, others, appId, menuId, formId));
        }
        ListAppVO listAppVo = new ListAppVO(appListPojos, resultThroughVo.getPageHelper().getRowsCount());
        resultThroughVo.setDataApp(listAppVo);
        return resultThroughVo;
    }


    private void setDetailShowScript(PaasFormDataEntityExt paasFormDataEntityExt, Integer businessType, JSONObject data, Map<String, FieldAttrEntity> explainMap, String attr, List<MobileDetailScriptPojo> scriptPojoList) {
        Boolean invisible = false;
        try {
            String corpid = paasFormDataEntityExt.getCorpid();
            Long dataId = paasFormDataEntityExt.getId();
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //协同团队
            userTeamService.getUserIdMap(Collections.singletonList(dataId), corpid, businessType, false, mainUserMap, coUserMap);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            //BeanUtil.copyProperties(businessProductListDTO, handlerExplainDTO);
            handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
            handlerExplainDTO.setOwnerId(mainUserMap.getOrDefault(dataId, new ArrayList<>()));
            handlerExplainDTO.setCoUserId(coUserMap.getOrDefault(dataId, new ArrayList<>()));
            handlerExplainDTO.setExplainList(new ArrayList<>(explainMap.values()));
            FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
            if (Objects.nonNull(fieldAttrEntity)) {
                invisible = ExplainUtil.isFieldNeedHide(fieldAttrEntity, handlerExplainDTO);
            }
        } catch (Exception e) {
            invisible = false;
        }

        FieldAttrEntity attrEntity = explainMap.get(attr);
        if (Objects.nonNull(attrEntity)) {
            MobileDetailScriptPojo pojo = new MobileDetailScriptPojo();
            Object moneyStr = moneyParseThrousandth(attrEntity,data,attr);
            if (invisible) {
                moneyStr = StringConstant.INVISIBLE_VALUE;
            }
            if (Objects.nonNull(moneyStr)) {
                pojo.setMoneyScript(moneyStr + UnitEnum.MONEY.getName());
                scriptPojoList.add(pojo);
            }
        }
    }

    private ListAppVO formatPurchaseAppList(List<PaasFormDataEntityExt> esEntities, Integer totalCount) throws XbbException {
        List<AppListPojo> appItemList = new ArrayList<>();
        for (PaasFormDataEntityExt formDataItem : esEntities) {
            JSONObject formData = formDataItem.getData();
            String titleShow = FastJsonHelper.getStringOrDefaultFromFormData(formData, PurchaseEnum.SHEET_NO.getAttr(), "");
            JSONObject others = new JSONObject();

            String totalAmount = FastJsonHelper.getStringOrDefaultFromFormData(formData, ContractEnum.AMOUNT.getAttr(), "0.0");
            others.put(ContractEnum.AMOUNT.getSaasAttr(), totalAmount + UnitEnum.MONEY.getName());

            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);


            appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
        }

        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appItemList);
        listAppVO.setTotalCount(totalCount);
        return  listAppVO;
    }

    /**
     * 设置bottomBlockInfo
     *
     * @param corpid
     * @param userId
     * @param bottomBlockInfo
     * @throws
     * @author long.rao
     * @date 2020-04-27 15:32
     */
    private void setBlockPojo(String corpid, String userId, JSONArray bottomBlockInfo) {
        if (StringUtil.isEmpty(userId)) {
            return;
        }
        List<String> userIdIn = new ArrayList<>();
        userIdIn.add(userId);
        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
        if (CollectionsUtil.isNotEmpty(userEntityList)) {
            List<CustomerUserPojo> customerUserPojos = new ArrayList<>();
            UserEntity userEntity = userEntityList.get(0);
            CustomerUserPojo customerUserPojo = new CustomerUserPojo();
            customerUserPojo.setUserId(userEntity.getUserId());
            customerUserPojo.setName(userEntity.getName());
            customerUserPojo.setAvatar(userEntity.getAvatar());
            customerUserPojo.setIsMain(userEntity.getIsMain());
            customerUserPojos.add(customerUserPojo);
            MobileDetailManagerBlockPojo mobileDetailManagerBlockPojo = new MobileDetailManagerBlockPojo(customerUserPojos);
            bottomBlockInfo.add(mobileDetailManagerBlockPojo);
        }
    }

    /**
     * 包装采购合同条件
     *
     * @param formDataListDTO 列表参数
     * @param fromBusinessType 从哪个业务进入
     * @throws
     * @author 徐俊杰
     * @date 2020/3/4 17:16
     * @since v1.0
     */
    private void packagePurchaseConditions(FormDataListDTO formDataListDTO, Integer fromBusinessType, Long supplierId) {
        if(Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(),fromBusinessType)) {
            List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
            //条件1-未付金额
            PurchaseEnum unFinishAmount = PurchaseEnum.UN_FINISH_AMOUNT;
            List<Object> value = Collections.singletonList(0);
            ConditionsEntityExt conditionsEntityExtUnFinishAmount = new ConditionsEntityExt(unFinishAmount.getAttr(), "", unFinishAmount.getFieldType(), ConditionEnum.GREATERTHAN.getSymbol(),
                    value);
            conditionsEntityExtList.add(conditionsEntityExtUnFinishAmount);
            //条件2-供应商id
            PurchaseEnum supplierIdEnum = PurchaseEnum.SUPPLIER_ID;
            List<Object> supplierIdList = Collections.singletonList(supplierId);
            ConditionsEntityExt conditionsEntityExtSupplierId = new ConditionsEntityExt(supplierIdEnum.getAttr(), "", supplierIdEnum.getFieldType(), ConditionEnum.EQUAL.getSymbol(),
                    supplierIdList);
            conditionsEntityExtList.add(conditionsEntityExtSupplierId);
            formDataListDTO.setConditions(conditionsEntityExtList);
        }
    }
}
